Search is not available for this dataset
name
stringlengths
2
112
description
stringlengths
29
13k
source
int64
1
7
difficulty
int64
0
25
solution
stringlengths
7
983k
language
stringclasses
4 values
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.io.InputStream; import java.io.PrintStream; import java.util.Scanner; public final class Solution { public static void main(String[] args) { parseSolveAndPrint(System.in, System.out); } public static void parseSolveAndPrint(InputStream in, PrintStream out) { Scanner scanner = new Scanner(in); Point start = new Point(scanner.nextInt(), scanner.nextInt()); Point finish = new Point(scanner.nextInt(), scanner.nextInt()); int n = scanner.nextInt(); Line[] lines = new Line[n]; for (int i = 0; i < n; i++) { lines[i] = new Line(scanner.nextInt(), scanner.nextInt(), scanner.nextInt()); } int steps = 0; for (Line line : lines) { if (line.doesIntersectSegment(start, finish)) steps++; } out.println(steps); } private static class Line { private double a; private double b; private double c; public Line(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public boolean doesIntersectSegment(Point start, Point finish) { double startDistance = a * start.x + b * start.y + c; double finishDistance = a * finish.x + b * finish.y + c; return startDistance * finishDistance < 0; } } private static class Point { private int x; private int y; public Point(int x, int y) { this.x = x; this.y = y; } } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; int a, b, c; long long get(long long x, long long y) { return a * x + b * y + c; } int main() { int x1, x2, y1, y2, n; scanf("%d%d%d%d%d", &x1, &y1, &x2, &y2, &n); int ans = 0; for (int i = 0; i < n; i++) { scanf("%d%d%d", &a, &b, &c); if ((get(x1, y1) ^ get(x2, y2)) < 0) ans++; } printf("%d\n", ans); return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
x1, y1 = list(map(int,input().split())) x2, y2 = list(map(int,input().split())) steps = 0 for i in int(input())*'_': a, b, c= list(map(int,input().split())) if (a * x1 + b * y1 + c) * (a * x2 + b * y2 + c) < 0: steps+=1 print(steps)
PYTHON3
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; int main() { long long hx, hy, ux, uy; cin >> hx >> hy >> ux >> uy; int n; cin >> n; long ans = 0; for (int i = 0; i < n; i++) { long long a, b, c; cin >> a >> b >> c; long long s1 = a * hx + b * hy + c; long long s2 = a * ux + b * uy + c; if (s1 < 0 && s2 > 0 || s1 > 0 && s2 < 0) { ans++; } } cout << ans; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; int main() { long long x, y, x1, y1; cin >> x >> y >> x1 >> y1; int n, cnt = 0; cin >> n; while (n--) { long long a, b, c; cin >> a >> b >> c; cnt += (a * x + b * y + c > 0) ^ (a * x1 + b * y1 + c > 0); } cout << cnt << endl; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; int main() { double nowx; long long x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2; int n; long long a, b, c, u1, u2, ans = 0; cin >> n; for (int i = 0; i < n; i++) { cin >> a >> b >> c; u1 = a * x1 + b * y1 + c; u2 = a * x2 + b * y2 + c; if ((u1 > 0 && u2 < 0) || (u1 < 0 && u2 > 0)) ans++; } cout << ans << endl; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:1024000000,1024000000") using namespace std; int main() { int T, i, j, k, ca = 0, n, m; int x1, y1, x2, y2; while (~scanf("%d%d%d%d", &x1, &y1, &x2, &y2)) { scanf("%d", &n); int ans = 0, a, b, c; while (n--) { scanf("%d%d%d", &a, &b, &c); long long first = 1LL * a * x1 + 1LL * b * y1 + c, second = 1LL * a * x2 + 1LL * b * y2 + c; if (first > 0 && second < 0) ans++; else if (first < 0 && second > 0) ans++; } printf("%d\n", ans); } }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner (System.in); int xa, ya, xb, yb; int n, ans=0, a, b, c; xa=s.nextInt(); ya=s.nextInt(); xb=s.nextInt(); yb=s.nextInt(); n=s.nextInt(); for (int i = 1; i <= n; ++i) {a=s.nextInt(); b=s.nextInt(); c=s.nextInt(); long tmp1 = (long )a * xa + (long)b * ya + c; long tmp2 = (long )a * xb + (long)b * yb + c; if (tmp1 > 0 && tmp2 < 0) ans++; else if (tmp1 < 0 && tmp2 > 0) ans++; } System.out.println(ans); }}
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> inline int Input() { int ret = 0; bool isN = 0; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') isN = 1; c = getchar(); } while (c >= '0' && c <= '9') { ret = ret * 10 + c - '0'; c = getchar(); } return isN ? -ret : ret; } inline void Output(long long x) { if (x < 0) { putchar('-'); x = -x; } int len = 0, data[20]; while (x) { data[len++] = x % 10; x /= 10; } if (!len) data[len++] = 0; while (len--) putchar(data[len] + 48); putchar('\n'); } #pragma comment(linker, "/STACK:124000000,124000000") using namespace std; int main() { int x1, y1, x2, y2; scanf("%d%d%d%d", &x1, &y1, &x2, &y2); int n; scanf("%d", &n); int ans = 0; while (n--) { int a, b, c; scanf("%d%d%d", &a, &b, &c); if (((long long)a * x1 + (long long)b * y1 + c) > 0 && ((long long)a * x2 + (long long)b * y2 + c) < 0) ans++; if (((long long)a * x1 + (long long)b * y1 + c) < 0 && ((long long)a * x2 + (long long)b * y2 + c) > 0) ans++; } printf("%d\n", ans); return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
def main(): x1, y1 = map(float, input().split()) x2, y2 = map(float, input().split()) n = int(input()) res = 0 for _ in range(n): a, b, c = map(float, input().split()) if a and b: x3, y3, x4, y4 = 0., -c / b, 1., -a / b elif a: x3, y4 = -c / a, 1. y3 = x4 = 0. else: x3 = y4 = 0. y3, x4 = -c / b, 1. ax = x1 - x3 ay = y1 - y3 bx = x2 - x3 by = y2 - y3 a = ax * y4 - ay * x4 b = bx * y4 - by * x4 if a < 0 < b or b < 0 < a: res += 1 print(res) if __name__ == '__main__': main()
PYTHON3
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); double x1, y1; double x2, y2; int n, ans = 0; cin >> x1 >> y1; cin >> x2 >> y2; double a1 = y1 - y2, b1 = x2 - x1, c1 = (a1 * x1 + b1 * y1) * (-1); cin >> n; for (long long int(i) = 0; (i) < (long long int)(n); (i)++) { double a2, b2, c2; cin >> a2 >> b2 >> c2; if (a1 == 0) { if (a2 == 0) continue; double y = (double)(-1) * c1 / b1; double x = (-1) * (c2 + y * b2) / a2; if ((x > x1 and x < x2) or (x < x1 and x > x2)) ans++; continue; } double y = (double)(c1 * a2 - c2 * a1) / (a1 * b2 - a2 * b1); double x = (double)(c1 + (double)b1 * y) * (-1) / a1; if (x > x1 && x < x2) ans++; else if (x < x1 && x > x2) ans++; else if (y < y1 && y > y2) ans++; else if (y > y1 && y < y2) ans++; } cout << ans << endl; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
x1, y1 = map(int, input().split()) x2, y2 = map(int, input().split()) n = int(input()) steps = 0 for i in range(n): a, b, c = map(int, input().split()) if (((a*x1 + b*y1 + c) < 0) != ((a*x2 + b*y2 + c) < 0)): steps += 1 print(steps)
PYTHON3
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int x1 = in.nextInt(),y1 = in.nextInt(); int x2 = in.nextInt(),y2 = in.nextInt(); int n = in.nextInt(); int ans = 0; for(int i=0;i<n;i++){ double a,b,c; a = in.nextDouble(); b = in.nextDouble(); c = in.nextDouble(); if((a*x1+b*y1+c)*(a*x2+b*y2+c)<1e-7) ans++; } System.out.println(ans); } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; int a[300], b[300], c[300]; int main() { long long x, y, v, w, n; cin >> x >> y >> v >> w >> n; for (int i = 0; i < n; i++) cin >> a[i] >> b[i] >> c[i]; int count = 0; for (int i = 0; i < n; i++) if (a[i] * x + b[i] * y + c[i] > 0 && a[i] * v + b[i] * w + c[i] < 0) count++; else if (a[i] * x + b[i] * y + c[i] < 0 && a[i] * v + b[i] * w + c[i] > 0) count++; cout << count << endl; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; void in() {} int main() { in(); long long x1, y1, x2, y2, cnt = 0; ; cin >> x1 >> y1 >> x2 >> y2; long long n, a, b, c, p1, p2; cin >> n; while (n--) { cin >> a >> b >> c; p1 = a * x1 + b * y1 + c; p2 = a * x2 + b * y2 + c; if ((p1 < 0 && p2 > 0) || (p1 > 0 && p2 < 0)) cnt++; } cout << cnt << endl; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; const double eps = 1e-8; const double PI = acos(-1.); const long long MOD = 1000000007; int sign(long long x) { return x < 0 ? -1 : x > 0; } int main() { int i, j, k, _T; long long x1, y1, x2, y2; while (cin >> x1 >> y1 >> x2 >> y2) { int n; scanf("%d", &n); int cnt = 0; while (n--) { long long a, b, c; cin >> a >> b >> c; int f1 = sign(a * x1 + b * y1 + c); int f2 = sign(a * x2 + b * y2 + c); if (f1 != f2) cnt++; } printf("%d\n", cnt); } return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import sys def pyes_no(condition) : if condition : print "YES" else : print "NO" def plist(a, s = ' ') : print s.join(map(str, a)) def rint() : return int(sys.stdin.readline()) def rints() : return map(int, sys.stdin.readline().split()) def rfield(n, m = None) : if m == None : m = n field = [] for i in xrange(n) : chars = sys.stdin.readline().strip() assert(len(chars) == m) field.append(chars) return field def digits(x, p) : digits = [] while x > 0 : digits.append(x % p) x /= p return digits x1, y1 = rints() x2, y2 = rints() n = rint() def intersect(x1, y1, x2, y2, line) : a, b, c = line return ((a * x1 + b * y1 + c) * (a * x2 + b * y2 + c)) < 0 count = 0 for i in range(n) : line = rints() count += intersect(x1, y1, x2, y2, line) print count
PYTHON
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; struct Point { long long int x, y; Point() { x = 0, y = 0; } Point(int a, int b) { x = a, y = b; } }; int main() { Point A, B; cin >> A.x >> A.y >> B.x >> B.y; int i, n; long long left, right, a, b, c; int ans = 0; cin >> n; for (i = 0; i < n; ++i) { cin >> a >> b >> c; left = a * A.x + b * A.y + c; right = a * B.x + b * B.y + c; if ((left < 0 && right > 0) || (left > 0 && right < 0)) { ++ans; } } cout << ans << "\n"; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
''' β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆβ–ˆβ–ˆβ–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–“β•¬β•¬β–“β–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–“β–“β•¬β•¬β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•¬β•¬β•¬β•¬β•¬β•¬β–ˆβ–ˆβ–ˆβ–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–ˆ β–ˆβ–ˆβ–ˆβ–“β–“β–“β–“β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆβ–ˆβ•¬β•¬β•¬β•¬β•¬β•¬β–“β–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆβ–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆ β–ˆβ–ˆβ–ˆβ–“β–ˆβ–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–ˆβ–ˆβ–ˆβ–“β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β•¬β•¬β•¬β•¬β–“β–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–ˆβ–“β•¬β•¬β•¬β•¬β•¬β–“β–“β–“β–“β–“β–“β–“β–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–ˆ β–ˆβ–ˆβ–ˆβ–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–ˆβ–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–ˆβ–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆ β–ˆβ–ˆβ–ˆβ–“β–ˆβ–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–“β–“β–“β–“β–“β–“β–ˆβ–“β–“β–“β–ˆβ–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–“β–“β–“β–“β–“β–ˆβ–ˆβ–“β–“β–“β–ˆβ–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–“β–“β–“β–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–“β–ˆβ–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–“β–ˆβ–“β–“β–“β–“β–ˆβ–ˆβ–“β–“β–“β–“β–ˆβ–ˆβ•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–ˆβ–ˆβ–ˆβ–“β–“β–“β–“β–“β–“β–“β–ˆβ–ˆβ–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–ˆβ–“β•¬β–“β•¬β•¬β–“β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–ˆβ–ˆβ–ˆβ–“β–“β–“β–“β–“β–“β–“β–“β–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–ˆβ–“β•¬β•¬β•¬β•¬β•¬β–“β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–ˆβ–“β–ˆβ–ˆβ–ˆβ–“β–“β–“β–ˆβ–ˆβ–ˆβ–ˆβ•¬β–“β–ˆβ–“β–“β•¬β•¬β•¬β–“β–“β–ˆβ–“β•¬β•¬β•¬β•¬β•¬β•¬β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–ˆβ–ˆβ–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β•¬β•¬β•¬β–“β–“β•¬β–“β–“β–ˆβ–ˆβ–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–ˆβ–ˆβ–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–ˆβ–ˆβ–“β–“β–“β–“β–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–“β–ˆβ–“β–“β–“β–“β–“β–ˆβ–ˆβ–ˆβ–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–“β–ˆβ–“β–“β–“β–“β–“β–ˆβ–ˆβ•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–ˆβ–“β–“β–“β–“β–ˆβ–ˆβ–ˆβ–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–“β–ˆβ–ˆβ–ˆβ–“β–“β•¬β•¬β•¬β•¬β•¬β•¬β•¬β•¬β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–“β–ˆβ–ˆβ–“β–“β•¬β•¬β•¬β•¬β•¬β•¬β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ ''' x1, y1 = map(int, input().split()) x2, y2 = map(int, input().split()) n = int(input()) ans = 0 for i in range(n): a, b, c = map(int, input().split()) sign1 = a * x1 + b * y1 + c sign2 = a * x2 + b * y2 + c if sign1 * sign2 < 0: ans += 1 print(ans)
PYTHON3
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> struct point { long long int x; long long int y; }; template <typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); } int main() { point A, B; long long int n, a, b, c; unsigned long int steps = 0; std::cin >> A.x; std::cin >> A.y; std::cin >> B.x; std::cin >> B.y; std::cin >> n; for (int i = 0; i < n; ++i) { std::cin >> a; std::cin >> b; std::cin >> c; if (sgn(a * A.x + b * A.y + c) != sgn(a * B.x + b * B.y + c)) { ++steps; } } std::cout << steps; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
home = map(int, raw_input().split()) university = map(int, raw_input().split()) n = input() lines = [] ans = 0 for road in xrange(n): ai, bi, ci = map(int, raw_input().split()) p = ai*home[0] + bi*home[1] + ci q = ai*university[0] + bi*university[1] + ci if (p < 0 and q > 0) or (p > 0 and q < 0): ans += 1 print ans
PYTHON
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.util.Scanner; public class Town { private static boolean intersect(int[] p1, int[] p2, long[] line) { return Math.signum(line[0] * p1[0] + line[1] * p1[1] + line[2]) != Math.signum(line[0] * p2[0] + line[1] * p2[1] + line[2]); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] home = new int[2]; home[0] = in.nextInt(); home[1] = in.nextInt(); int[] university = new int[2]; university[0] = in.nextInt(); university[1] = in.nextInt(); int n = in.nextInt(); long[][] roads = new long[n][3]; for (int i = 0; i < n; i++) { for (int j = 0; j < 3; j++) { roads[i][j] = in.nextLong(); } } int r = 0; for (int i = 0; i < roads.length; i++) { if (intersect(home, university, roads[i])) { r++; } } System.out.println(r); } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; long long n, ans, hx, hy, ux, uy, data[300][3]; bool test(long long a, long long b, long long c) { return (a * hx + b * hy + c > 0) ^ (a * ux + b * uy + c > 0); } int main() { cin >> hx >> hy >> ux >> uy >> n; for (int i = 0; i < n; i++) { long long a, b, c; cin >> a >> b >> c; if (test(a, b, c)) { ans++; } } cout << ans << "\n"; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; int main() { long long hx, hy, ux, uy, a, b, c; cin >> hx >> hy >> ux >> uy; long long n, cnt = 0; cin >> n; for (int i = 0; i < n; ++i) { cin >> a >> b >> c; if ((a * hx + b * hy + c) < 0 && (a * ux + b * uy + c) > 0) cnt++; else if ((a * hx + b * hy + c) > 0 && (a * ux + b * uy + c) < 0) cnt++; } cout << cnt << endl; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
x1,y1=map(int,raw_input().split()) x2,y2=map(int,raw_input().split()) n=int(raw_input()) rs=0 for i in xrange(n): a,b,c=map(int,raw_input().split()) if ((a*x1+b*y1+c)*(a*x2+b*y2+c))<0: rs+=1 print rs
PYTHON
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; double ax, ay, bx, by; bool check(double x, double y) { int ok = 0; if (x <= max(ax, bx) && x >= min(ax, bx)) ok++; if (y <= max(ay, by) && y >= min(ay, by)) ok++; return ok == 2 ? true : false; } double a, b, c, p, q; void cal(double &cx, double &cy) { if (fabs(b) < 1e-8) { cx = -c / a; cy = p * cx + q; } else { cx = (-c - b * q) / (b * p + a); cy = p * cx + q; } } int main() { int n, x, y, xx, yy; scanf("%d%d%d%d", &x, &y, &xx, &yy); ax = (double)x, ay = (double)y; bx = (double)xx, by = (double)yy; scanf("%d", &n); int ans = 0; for (int i = 0; i < n; ++i) { scanf("%lf %lf %lf", &a, &b, &c); if (x == xx) { if (fabs(b) < 1e-8) continue; bool ok = check(ax, (-c - a * ax) / b); if (ok) ans++; } else { p = (by - ay) / (bx - ax); q = (ay * bx - by * ax) / (bx - ax); double cx, cy; if (fabs(-a / b - p) < 1e-8) continue; cal(cx, cy); bool ok = check(cx, cy); if (ok) ans++; } } cout << ans << endl; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
x1,y1 = map(int,input().split()) x2,y2 = map(int,input().split()) n = int(input()) num = 0 for i in range(n): a,b,c = map(int,input().split()) num += (a * x1 + b * y1 + c > 0) != (a * x2 + b * y2 + c > 0) print(num)
PYTHON3
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.io.*; import java.util.*; public class Solution { StringTokenizer st; BufferedReader in; PrintWriter out; void solve() throws IOException { //in = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"), "ISO-8859-1")); ///out = new PrintWriter(new OutputStreamWriter(new FileOutputStream("output.txt"), "ISO-8859-1")); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); Locale.setDefault(Locale.ENGLISH); int[] p1 = new int[]{nextInt(), nextInt()}; int[] p2 = new int[]{nextInt(), nextInt()}; int n = nextInt(); int[][] l = new int[n][3]; int ans = 0; for (int i = 0; i < n; i++) { l[i] = new int[]{nextInt(), nextInt(), nextInt()}; if ((l[i][0] * 1.0 * p1[0] + l[i][1] * 1.0 * p1[1] + l[i][2]) * (l[i][0] * 1.0 * p2[0] + l[i][1] * 1.0 * p2[1] + l[i][2]) < 0) { ans++; } } out.print(ans); in.close(); out.close(); } public static void main(String[] args) throws IOException { new Solution().solve(); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.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()); } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.util.*; public class CrazyTown499C { public static void main(String[] args) { // Set up scanner Scanner sc = new Scanner(System.in); // System.out.println("Enter x of home"); long xh = sc.nextLong(); // System.out.println("Enter y of home"); long yh = sc.nextLong(); // System.out.println("Enter x of university"); long xu = sc.nextLong(); // System.out.println("Enter y of university"); long yu = sc.nextLong(); double smallx = (double)Math.min(xh, xu); double largex = (double)Math.max(xh, xu); double smally = (double)Math.min(yh, yu); double largey = (double)Math.max(yh, yu); // Find equation of line between you and the university long a; long b; long c; if (xh == xu) // Vertical line { a = 1; b = 0; c = -xh; } else // General case { long dx = xu - xh; long dy = yu - yh; a = -dy; b = dx; c = (-dx * yh) + (dy * xh); } // System.out.println("The equation is " + a + "x + " + b + "y + " + c + " = 0"); // Find out how many of the lines intersect your line between the two endpoints int intlines = 0; // System.out.println("Enter number of roads"); int n = sc.nextInt(); for (int i=0; i<n; i++) { // System.out.println("Input d"); long d = sc.nextLong(); // System.out.println("Input e"); long e = sc.nextLong(); // System.out.println("Input f"); long f = sc.nextLong(); if (a*e != b*d) // Not parallel--have an intersection (x,y) { long det = (a*e - b*d); double x = (b*f - c*e) / (double)det; double y = (c*d - a*f) / (double)det; if (smallx <= x && x <= largex && smally <= y && y <= largey) { intlines++; // Found an intersecting line } } } System.out.println(intlines); } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Scanner; public class Main { static FasterScanner sc; //static ArrayList<Integer>[] arr; //static boolean[] b; public static void main(String args[] ) throws Exception { FasterScanner sc= new FasterScanner(); long x1 = sc.nextLong(), y1 = sc.nextLong(), x2 = sc.nextLong(), y2 = sc.nextLong(); int n = sc.nextInt(); int cnt = 0, x = 0; while(n-->0){ long arr[] = new long[3]; arr[0] = sc.nextLong(); arr[1] = sc.nextLong(); arr[2] = sc.nextLong(); long a = arr[0]*x1 + arr[1]*y1 + arr[2] , b = arr[0]*x2 + arr[1]*y2 + arr[2]; if(Long.signum(a) != Long.signum(b)) cnt++; } System.out.println(cnt); } public static int min(int a,int b, int c){ if(a<b){ if(c<a) return c; return a; } else{ if(c<b) return c; return b; } } public static class FasterScanner { 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 = System.in.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 int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; double x1, y_1, x2, y2; int n; int main() { cin >> x1 >> y_1 >> x2 >> y2; cin >> n; double a, b, c; int res = 0; for (int i = 0; i < n; i++) { cin >> a >> b >> c; if (a == 0) { res += ((y_1 > -c / b) + (y2 > -c / b) == 1); } else if (b == 0) { res += ((x1 > -c / a) + (x2 > -c / a) == 1); } else { res += ((a * x1 + b * (y_1 + c / b)) * (a * x2 + b * (y2 + c / b)) < 0); } } cout << res << endl; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class P5_CrazyTown { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); long xs = Long.parseLong(st.nextToken()), ys = Long.parseLong(st.nextToken()); st = new StringTokenizer(br.readLine()); long xu = Long.parseLong(st.nextToken()), yu = Long.parseLong(st.nextToken()); int n = Integer.parseInt(br.readLine()); //Line[] l = new Line[n]; long a,b,c; int r = 0; for(int i = 0 ; i < n ; i++) { st = new StringTokenizer(br.readLine()); a = Long.parseLong(st.nextToken()); b = Long.parseLong(st.nextToken()); c = Long.parseLong(st.nextToken()); if((a*xs + b*ys + c) < 0 && (a*xu + b*yu + c) > 0 || (a*xs + b*ys + c) > 0 && (a*xu + b*yu + c) < 0) r++; } System.out.println(r); } /*static class Point { int x,y; public Point(int a , int b) { x = a; y = b; } } static class Line { double a,b,c; public Line(double x , double y , double z) { if(y == 0) { a = 1.0; c = z/x; } else { a = x/y; b = 1; c = z/y; } } }*/ }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
//package CF; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { public static void main(String[] args) throws IOException { Scanner bf = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); Point me = new Point(bf.nextInt(), bf.nextInt()); Point uni = new Point(bf.nextInt(), bf.nextInt()); int ans = 0; int n = bf.nextInt(); for (int i = 0; i < n; i++) { long a = bf.nextInt(); long b = bf.nextInt(); int c = bf.nextInt(); ans += (a*me.x + b*me.y + c > 0 )^(a*uni.x + b*uni.y + c > 0 )?1:0; } out.println(ans); out.flush(); out.close(); } static class Point{ int x, y; Point(int a, int b) { x = a; y = b; } } 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
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; int main() { long long int x1, y1, x2, y2, a, b, c, p1, p2; cin >> x1 >> y1 >> x2 >> y2; long long int n; cin >> n; long long int ans = 0; for (int i = 0; i < n; i++) { cin >> a >> b >> c; p1 = a * x1 + b * y1 + c; p2 = a * x2 + b * y2 + c; if ((p1 >= 0 && p2 >= 0) || (p1 <= 0 && p2 <= 0)) ans = ans; else ans = ans + 1; } cout << ans << endl; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <cstdlib> #include <cstdarg> #include <cassert> #include <cctype> // tolower #include <ctime> #include <cmath> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <stdexcept> #include <map> #include <tuple> #include <unordered_map> #include <set> #include <list> #include <stack> #include <queue> #include <vector> #include <string> #include <limits> #include <utility> #include <memory> #include <numeric> #include <iterator> #include <algorithm> #include <functional> /* * g++ -g -std=c++11 -DBUG -D_GLIBCXX_DEBUG -Wall -Wfatal-errors -o cforce{,.cpp} * * TODO: * C++ dataframe * stl11 -> c++11 standard template lib in c++98 * overload >> for map and set, using (insert) iterator * chmod:: consider an algorithm stable to int64 overflow * shortest path algorithm * shortest path in a tree * maximum network flow * partial idx/iter sort * a prime number generator which traverses prime numbers w/ ++ * a divisor generator which traverses divisors efficiently * Apply1st ?! * Apply2nd and bind2nd ?! * count_if ( a.begin(), a.end(), a.second < x ) * Arbitrary-precision arithmetic / Big Integer / Fraction - rational num * tuple class --> cplusplus.com/reference/tuple * get<1>, get<2>, bind2nd ( foo ( get<2> pair ), val ) * isin( const T & val, first, last ) * fuinction composition in c++ * blogea.bureau14.fr/index.php/2012/11/function-composition-in-c11/ * cpp-next.com/archive/2010/11/expressive-c-fun-with-function-composition/ * TimeWrapper -- accumulate time of a function call * stackoverflow.com/questions/879408 * hash map -- possible hash value & obj % some_big_prime [ b272 ] * lower level can be a simple map to resolve hash collisions * add explicit everywhere necessary * bloom filters * heap -> how to update values in place / increase-key or decrease-key ... IterHeap ?! * median maintaince --> max_heap / min_heap * prim's min spaning tree alg. O ( m log n ) using heap contianing V - X vertices * kruskal algorithm minimum cost spanning tree with union find data structure * unique_ptr * hufman codes * simple arithmatic tests * longest common subsequence using seq. alignment type algorithm * longest common substring ( consequative subsequeance ) * Graham scan; en.wikipedia.org/wiki/Graham_scan * problem/120/F -- how to extend in order to calculate all-pair distances in a tree * compile time prime number calculator using templates * swith to type_cast < T1, T2 > for val2str & str2val * overload plus<> for two vectors?! * overloading operator << for tuple: * stackoverflow.com/questions/9247723 * bitmask class with iterator protocol * ??? segment tree +++ interval tree * ??? an lru cache: a heap which maintains last access, an a map which maintains key:value * ??? in lazy-union how to query size of a connected component( 437/D ) */ /* * @recepies * ---------------------------------------------- * odd / even * transform ( x.begin(), x.end(), x.begin(), bind2nd( modulus<int>(), 2 )); * count_if ( x.begin(), x.end(), bind2nd( modulus < int > (), 2)); * Apply2nd * max_element ( m.begin(), m.end(), Apply2nd < string, int , less < int > > ) * sort ( a.begin(), a.end(), Apply2nd < char, int , greater< int > > ) * count_if ( m.begin(), m.end(), Apply2nd < string, int, modulus < int > > ) * accumulate ( m.begin(), m.end(), 0.0, Apply2nd < int, double, plus < double > > ) * accumulate ( m.begin( ), m.end( ), pair < int, double> ( 0 , 0.0 ) , operator+ < int, double > ) * abs_diff * adjacent_difference ( a.begin(), a.end(), adj_diff.begin( ), abs_diff < int > ( ) ) * accumulate ( a.begin(), a.end(), 0, abs_diff < int > ( ) ) * erase * a.erase ( remove_if ( a.begin( ), a.end( ), bind2nd ( less < int >( ), 0 ) ), a.end( ) ) * a.erase ( remove ( a.begin( ), a.end( ), b.begin( ), b.end( ) ), a.end ( ) ) * binding * bind2nd ( mem_fun_ref (& ClassName::m_func ), arg ) // binds the argument of the object * iterator generators * generate_n ( back_inserter ( a ), n, rand ); // calls push_back * generate_n ( inserter( a, a.begin( ) + 5 ), 10, RandInt( 0 , 100 ) ) // calls insert * copy ( foo.begin( ), foo.end( ), insert_iterator < list < double > > ( bar, bar.begin( ) + 5 )) * copy ( a.begin( ), a.end( ), ostream_iterator < double > ( cout, ", " )) * accumulate ( m.begin( ), m.end( ), pair < int, double> ( 0 , 0.0 ) , operator+ < int, double > ) * transform (numbers.begin(), numbers.end(), lengths.begin(), mem_fun_ref(&string::length)); */ /* * @good read * ---------------------------------------------- * [ partial ] template specialization * cprogramming.com/tutorial/template_specialization.html * function composition * cpp-next.com/archive/2010/11/expressive-c-fun-with-function-composition */ /* * @prob set * ---------------------------------------------- * purification --> c330 */ /* * @limits * ---------------------------------------------- * int 31 2.14e+09 * long int 31 2.14e+09 * unsigned 32 4.29e+09 * long unsigned 32 4.29e+09 * size_t 32 4.29e+09 * long long int 63 9.22e+18 * long long unsigned 64 1.84e+19 */ /* * issues * ---------------------------------------------- * stackoverflow.com/questions/10281809 * mem_fun -> func_obj ( pointer to instance, origanal argument ) * bind1st ( mem_fun ( & ClassName::m_func ), this ) // binds obj of the class * bind1st takes 'const T &' as the first argument */ /* * typedef / define * ---------------------------------------------- */ typedef long long int int64; typedef unsigned long long int uint64; #ifndef M_PI #define M_PI 3.14159265358979323846L #endif #define DOUBLE_INF std::numeric_limits< double >::infinity() #define DOUBLE_NAN std::numeric_limits< double >::quiet_NaN() #define __STR__(a) #a #define STR(a) __STR__(a) #define ASSERT(expr, msg) \ if (!( expr )) \ throw std::runtime_error(__FILE__ ":" STR(__LINE__) " - " msg); #define DECLARE( X ) \ typedef shared_ptr < X > X ## _shared_ptr; \ typedef const shared_ptr < X > X ## _const_shared_ptr; #ifdef BUG #define DEBUG(var) { std::cout << #var << ": " << (var) << std::endl; } #define COND_DEBUG(expr, var) if (expr) \ { std::cout << #var << ": " << (var) << std::endl; } #define EXPECT(expr) if ( ! (expr) ) std::cerr << "Assertion " \ << #expr " failed at " << __FILE__ << ":" << __LINE__ << std::endl; #else #define DEBUG(var) #define COND_DEBUG(expr, var) #define EXPECT(expr) #endif #define DBG(v) std::copy( v.begin(), v.end(), std::ostream_iterator < typeof( *v.begin() )> ( std::cout, " " ) ) #if __cplusplus < 201100 #define move( var ) var #endif /* * http://rootdirectory.de/wiki/SSTR() * usage: * SSTR( "x^2: " << x*x ) */ #define SSTR( val ) dynamic_cast< std::ostringstream & >( std::ostringstream() << std::dec << val ).str() using namespace std; /* https://www.quora.com/C++-programming-language/What-are-some-cool-C++-tricks */ // template <typename T, size_t N> // char (&ArraySizeHelper(T (&array)[N]))[N]; // #define arraysize(array) (sizeof(ArraySizeHelper(array))) /* * forward decleration * ---------------------------------------------- */ class ScopeTimer; /* * functional utils * ---------------------------------------------- */ template < typename T > struct abs_diff : binary_function < T, T, T > { typedef T value_type; inline value_type operator( ) ( const value_type & x, const value_type & y ) const { return abs( x - y ); } }; // template < class InputIterator, class T > // class isin : public binary_function < InputIterator, InputIterator, bool > // { // public: // typedef T value_type; // // isin ( const InputIterator & first, const InputIterator & last ): // m_first ( first ), m_last ( last ) { } // // bool operator ( ) ( const value_type & val ) const // { // return find ( m_first, m_last, val ) != m_last; // } // private: // const InputIterator m_first, m_last; // } template < typename value_type, typename cont_type > class isin : public unary_function < value_type, bool > { public: isin( const cont_type & vals ): m_vals ( vals ) { }; bool operator ( ) ( const value_type & x ) const { return find ( m_vals.begin( ), m_vals.end( ), x ) != m_vals.end( ); } private: const cont_type m_vals; }; /* * max_element, min_element, count_if ... on the 2nd element * eg: max_element ( m.begin(), m.end(), Apply2nd < string, int , less < int > > ) */ template < class T1, class T2, class BinaryOperation > class Apply2nd : binary_function < typename std::pair < T1, T2 >, typename std::pair < T1, T2 >, typename BinaryOperation::result_type > { public: typedef T1 first_type; typedef T2 second_type; typedef typename BinaryOperation::result_type result_type; typedef typename std::pair < first_type, second_type > value_type; inline result_type operator( ) ( const value_type & x, const value_type & y ) const { return binary_op ( x.second , y.second ); } private: BinaryOperation binary_op; }; /* * algo utils * ---------------------------------------------- */ /** * count the number of inversions in a permutation; i.e. how many * times two adjacent elements need to be swaped to sort the list; * 3 5 2 4 1 --> 7 */ template < class InputIterator > typename iterator_traits<InputIterator>::difference_type count_inv ( InputIterator first, InputIterator last ) { typedef typename iterator_traits<InputIterator>::difference_type difference_type; typedef typename iterator_traits<InputIterator>::value_type value_type; list < value_type > l; /* list of sorted values */ difference_type cnt = 0; for ( difference_type n = 0; first != last; ++first, ++n ) { /* count how many elements larger than *first appear before *first */ typename list < value_type >::iterator iter = l.begin( ); cnt += n; for ( ; iter != l.end( ) && * iter <= * first; ++ iter, -- cnt ) ; l.insert( iter, * first ); } return cnt; } template < class ForwardIterator, class T > inline void fill_inc_seq ( ForwardIterator first, ForwardIterator last, T val ) { for ( ; first != last; ++first, ++val ) * first = val; } template <class ForwardIterator, class InputIterator > ForwardIterator remove ( ForwardIterator first, ForwardIterator last, InputIterator begin, InputIterator end ) { ForwardIterator result = first; for ( ; first != last; ++ first ) if ( find ( begin, end, *first ) == end ) { *result = *first; ++result; } return result; } /* stackoverflow.com/questions/1577475 */ template < class RAIter, class Compare > class ArgSortComp { public: ArgSortComp ( const RAIter & first, Compare comp ): m_first ( first ), m_comp( comp ) { } inline bool operator() ( const size_t & i, const size_t & j ) const { return m_comp ( m_first[ i ] , m_first[ j ] ); } private: const RAIter & m_first; const Compare m_comp; }; /*! * usage: * vector < size_t > idx; * argsort ( a.begin( ), a.end( ), idx, less < Type > ( ) ); */ template < class RAIter, class Compare=less< typename RAIter::value_type > > void argsort( const RAIter & first, const RAIter & last, vector < size_t > & idx, Compare comp = Compare()) // less< typename RAIter::value_type >() ) { const size_t n = last - first; idx.resize ( n ); for ( size_t j = 0; j < n; ++ j ) idx[ j ] = j ; stable_sort( idx.begin(), idx.end(), ArgSortComp< RAIter, Compare >( first, comp )); } template < class RAIter, class Compare > class IterSortComp { public: IterSortComp ( Compare comp ): m_comp ( comp ) { } inline bool operator( ) ( const RAIter & i, const RAIter & j ) const { return m_comp ( * i, * j ); } private: const Compare m_comp; }; /*! * usage: * vector < list < Type >::const_iterator > idx; * itersort ( a.begin( ), a.end( ), idx, less < Type > ( ) ); */ template <class INIter, class RAIter, class Compare> void itersort ( INIter first, INIter last, vector < RAIter > & idx, Compare comp ) { /* alternatively: stackoverflow.com/questions/4307271 */ idx.resize ( distance ( first, last ) ); for ( typename vector < RAIter >::iterator j = idx.begin( ); first != last; ++ j, ++ first ) * j = first; sort ( idx.begin( ), idx.end( ), IterSortComp< RAIter, Compare > (comp ) ); } /* * string utils * ---------------------------------------------- */ inline void erase ( string & str, const char & ch ) { binder2nd < equal_to < char > > isch ( equal_to< char >(), ch ); string::iterator iter = remove_if ( str.begin(), str.end(), isch ); str.erase ( iter, str.end() ); } inline void erase ( string & str, const string & chrs ) { isin < char, string > isin_chrs ( chrs ); string::iterator iter = remove_if ( str.begin(), str.end(), isin_chrs ); str.erase ( iter, str.end() ); } template < typename value_type> inline string val2str ( const value_type & x ) { ostringstream sout ( ios_base::out ); sout << x; return sout.str(); } template < typename value_type> inline value_type str2val ( const string & str ) { istringstream iss ( str, ios_base::in ); value_type val; iss >> val; return val; } vector< string > tokenize( const string & str, const char & sep ) { /*! * outputs empty tokens and assumes str does not start with sep * corner cases: * empty string, one char string, * string starting/ending with sep, all sep, end with two sep */ vector < string > res; string::const_iterator follow = str.begin(), lead = str.begin(); while ( true ) { while ( lead != str.end() && * lead != sep ) ++ lead; res.push_back ( string( follow, lead ) ); if ( lead != str.end () ) follow = 1 + lead ++ ; else break; } return res; } /*! * chunk a string into strings of size [ at most ] k */ void chunk ( const string::const_iterator first, const string::const_iterator last, const size_t k, const bool right_to_left, list < string > & str_list ) { str_list.clear( ); if ( right_to_left ) /* chunk from the end of the string */ for ( string::const_iterator i, j = last; j != first; j = i ) { i = first + k < j ? j - k : first; str_list.push_back ( string ( i, j ) ); } else /* chunk from the begining of the string */ for ( string::const_iterator i = first, j; i != last; i = j ) { j = i + k < last ? i + k : last; str_list.push_back ( string ( i, j ) ); } } /*! * next lexicographically smallest string * within char set a..z */ string & operator++( string & s ) { /* find the first char from right less than 'z' */ string::reverse_iterator j = find_if( s.rbegin( ), s.rend( ), bind2nd( less < char > ( ), 'z' )); if ( j != s.rend( )) { ++ *j; fill( s.rbegin( ), j, 'a' ); } else s.assign( s.length( ) + 1, 'a' ); return s; } /*! if a starts with b */ inline bool starts_with( const string & a, const string & b ) { return !( a.size() < b.size() || mismatch( begin(b), end(b), begin(a) ).first != end(b) ); } /*! prefix tree */ auto get_prefix_tree( const vector< string > & word ) -> vector< map< char, size_t > > { typedef map< char, size_t > node; /* empty string as the first element */ vector< node > tree(1); for( const auto & w: word ) { /* start with empty string as the root node */ size_t root = 0; for( const auto & a : w ) { auto & ref = tree[ root ][ a ]; if ( ref == 0 ) /* new prefix, add to the end of tree */ { ref = tree.size(); tree.push_back( node() ); } root = ref; } } return tree; } /*! * getline ( cin, str ) * requires ctrl-D * cin >> str; does not pass after space char */ /* * number utils * ---------------------------------------------- */ class BigInteger { #if ULONG_MAX <= 1 << 32 typedef long long unsigned val_type; #else typedef long unsigned val_type; #endif const static int WSIZE = 32; const static val_type BASE = 1LL << WSIZE; public: private: list < val_type > val; /* val[ 0 ] is most significant */ bool pos; /* true if sign is positive */ }; /** * greatest common divisor - Euclid's alg. */ template < typename value_type > inline value_type gcd ( value_type a, value_type b ) { return ! b ? a : gcd( b, a % b ); } /** * prime factorization */ template < class T > void prime_factors( T n, map < T, size_t > & fac ) { for ( T k = 2; n > 1; ++ k ) if ( ! ( n % k ) ) { size_t & ref = fac[ k ]; while ( ! ( n % k ) ) { ++ ref; n /= k; } } } /* abs diff - safe for unsigned types */ template < class T > inline T absdiff( T a, T b ) { return a < b ? b - a : a - b; } namespace { template < class T > pair < T, T > __extgcd ( const T & x0, const T & y0, const T & x1, const T & y1, const T & r0, const T & r1 ) { const T q = r0 / r1; const T r2 = r0 % r1; if ( ! ( r1 % r2 ) ) return make_pair < T, T > ( x0 - q * x1, y0 - q * y1 ); const T x2 = x0 - q * x1; const T y2 = y0 - q * y1; return __extgcd ( x1, y1, x2, y2, r1, r2 ); } } /** * extended euclidean algorithm: a x + b y = gcd( a, b) * en.wikipedia.org/wiki/Extended_Euclidean_algorithm */ template < class value_type > inline pair < value_type, value_type > extgcd ( value_type a, value_type b ) { return a % b ? __extgcd < value_type > ( 1, 0, 0, 1, a, b ) : make_pair < value_type, value_type > ( 0, 1 ); } /** * modular multiplicative inverse * en.wikipedia.org/wiki/Modular_multiplicative_inverse */ template < class value_type > inline value_type modinv ( value_type a, value_type m ) { const pair < value_type, value_type > coef ( extgcd( a, m ) ); /* a needs to be coprime to the modulus, or the inverse won't exist */ if ( a * coef.first + m * coef.second != 1 ) throw runtime_error ( val2str( a ) + " is not coprime to " + val2str( m )); /* return a pos num between 1 & m-1 */ return ( m + coef.first % m ) % m; } inline bool isnan ( const double & a ) { return ! ( a == a ); } template < typename value_type > inline value_type mini ( int n, ... ) { va_list vl; va_start (vl, n); value_type res = va_arg ( vl, value_type ); for ( int i = 1; i < n; ++i ) { const value_type val = va_arg ( vl, value_type ); res = min ( res, val ); } va_end( vl ); return res; } template < typename value_type > inline value_type maxi ( int n, ... ) { va_list vl; va_start (vl, n); value_type res = va_arg ( vl, value_type ); for ( int i = 1; i < n; ++i ) { const value_type val = va_arg ( vl, value_type ); res = max ( res, val ); } va_end( vl ); return res; } // XXX look this up how is this implemented template < class T > inline int sign ( const T & x ) { if ( x == T() ) return 0; else if ( x < T() ) return -1; else return 1; } /* * change moduluos from n to m */ string chmod ( string num, const unsigned n, const unsigned m ) { const char * digit = "0123456789abcdefghijklmnopqrstuvwxyz"; transform ( num.begin(), num.end(), num.begin(), ::tolower ); isin < char, string > is_alpha_num ( digit ); assert ( find_if ( num.begin( ), num.end( ), not1 ( is_alpha_num ) ) == num.end( )); unsigned long long int val ( 0 ); if ( n == 10U ) { istringstream iss ( num, ios_base::in ); iss >> val; } else for ( string::const_iterator iter = num.begin( ); iter != num.end( ); ++ iter ) val = val * n + ( 'a' <= *iter ? *iter - 'a' + 10U : *iter - '0'); if ( m == 10U ) { ostringstream sout ( ios_base::out ); sout << val; return sout.str ( ); } else { string res; for ( ; val ; val /= m ) res.push_back( digit [ val % m ] ); return res.length( ) ? string( res.rbegin( ), res.rend( )) : "0"; } } template < class value_type > /* a^n mod m */ value_type powmod ( value_type a, const value_type & n, const value_type & m ) { if ( a == 1 || ! n ) return m != 1 ? 1 : 0; value_type res = 1; for ( value_type k = 1; k <= n; a = a * a % m, k = k << 1 ) if ( k & n ) res = ( res * a ) % m; return res; } template < class T > inline T atan(const T & x, const T & y) { return atan( y / x ) + ( x < 0 ) * M_PI; } /* * Fermat pseudoprime test * www.math.umbc.edu/~campbell/Computers/Python/numbthy.py * NOTE: since return type is bool, and powmod may break for ints, * the argument is always casted to long long */ inline bool is_pseudo_prime ( const long long & a ) { /* all the primes less than 1000 ( 168 primes )*/ const long long p [ ] = { 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73, 79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157, 163,167,173,179,181,191,193,197,199,211,223,227,229,233,239, 241,251,257,263,269,271,277,281,283,293,307,311,313,317,331, 337,347,349,353,359,367,373,379,383,389,397,401,409,419,421, 431,433,439,443,449,457,461,463,467,479,487,491,499,503,509, 521,523,541,547,557,563,569,571,577,587,593,599,601,607,613, 617,619,631,641,643,647,653,659,661,673,677,683,691,701,709, 719,727,733,739,743,751,757,761,769,773,787,797,809,811,821, 823,827,829,839,853,857,859,863,877,881,883,887,907,911,919, 929,937,941,947,953,967,971,977,983,991,997 }; const size_t n = sizeof( p ) / sizeof ( p[ 0 ] ); if ( a < p[ n - 1 ] + 1) return binary_search ( p, p + n , a ); if ( find_if ( p, p + n, not1 ( bind1st ( modulus< long long >( ), a ))) != p + n ) return false; const size_t k = a < 9006401LL ? 3 : a < 10403641LL ? 4 : a < 42702661LL ? 5 : a < 1112103541LL ? 6 : 7; for ( size_t j = 0; j < k; ++ j ) if ( powmod ( p[ j ], a - 1, a ) != 1 ) return false; return true; } /* * returns a sorted vector of all primes less than or equal to n * maximum adj diff of all primes less than 1e5 is 72 ( 114 for 1e6 ) */ template < typename value_type > vector < value_type > get_primes ( const value_type n ) { #ifdef BUG ScopeTimer scope_timer ( "vector < value_type > get_primes ( const value_type n )" ); #endif // typedef typename vector < value_type >::iterator iterator; vector < value_type > primes; for ( value_type k = 2 ; k <= n; ++ k ) if ( is_pseudo_prime ( k ) ) { // FIXME this is very stupid // const value_type sqrt_k = 1 + static_cast < value_type > ( sqrt ( k + 1 ) ); // iterator iend = upper_bound ( primes.begin( ), primes.end( ), sqrt_k ); // if ( find_if ( primes.begin( ), iend, not1 ( bind1st ( modulus< value_type >( ), k ) ) ) != iend ) // continue; primes.push_back ( k ); } return primes; } template < class T > /* prime factorization */ vector < pair < T, size_t > > get_prime_fac( T a ) { vector < pair < T, size_t > > fac; size_t k = 0; while (!(a % 2)) { a /= 2; ++ k; } if ( k != 0 ) fac.push_back( make_pair(2, k)); k = 0; while (!(a % 3)) { a /= 3; ++ k; } if ( k != 0 ) fac.push_back( make_pair(3, k)); for ( T j = 5; j * j < a + 1 && a > 1 && j < a + 1; j += 4 ) { size_t k = 0; while (!(a % j)) { a /= j; ++ k; } if ( k != 0 ) fac.push_back( make_pair(j, k)); j += 2; k = 0; while (!(a % j)) { a /= j; ++ k; } if ( k != 0 ) fac.push_back( make_pair(j, k)); } if ( a > 1 ) fac.push_back( make_pair(a, 1)); return fac; } template < class T > /* generates all divisors from vector of prime factorization */ void gen_div( T a, vector < T > & divs, typename vector < pair < T, size_t > >::const_iterator iter, typename vector < pair < T, size_t > >::const_iterator last ) { if ( iter != last ) { auto next = iter + 1; const auto k = iter->second + 1; const auto prime = iter->first; for ( size_t j = 0; j < k; ++ j ) { gen_div(a, divs, next, last); a *= prime; } } else divs.push_back( a ); } template < class T > T n_choose_k ( T n, T k ) { if ( k > n ) return 0; const T lb = min ( k, n - k ) + 1; const T ub = n - lb + 1; T res = 1, j = 2; while ( n > ub && j < lb) { res *= n--; while ( j < lb and ! (res % j) ) res /= j++; } while ( n > ub ) res *= n--; return res; } /** * median calculator, using two heaps */ template < class InputIter > inline pair < typename InputIter::value_type, typename InputIter::value_type > median ( InputIter first, InputIter last ) { typedef typename InputIter::value_type value_type; typedef pair< value_type, value_type > result_type; /* * max_heap: * - the lower half of the elements * - the biggest of such elements is on the top */ vector < value_type > max_heap, min_heap; /* * comp argument to heap algorithm should provide * 'strict weak ordering'; in particular * not2 ( less < value_type > ) * does not have such a strict weak ordering; */ less < value_type > max_heap_comp; greater < value_type > min_heap_comp; if ( first == last ) /* corner case: empty vector */ throw runtime_error ( "median of an empty vector is undefined!" ); InputIter iter = first; max_heap.push_back ( * iter ); for ( ++iter ; iter != last; ++ iter ) if ( * iter < max_heap.front() ) { max_heap.push_back ( * iter ); push_heap ( max_heap.begin(), max_heap.end(), max_heap_comp ); if ( min_heap.size() + 1 < max_heap.size() ) { /* max_heap has got too large */ min_heap.push_back( max_heap.front() ); push_heap( min_heap.begin(), min_heap.end(), min_heap_comp ); pop_heap( max_heap.begin(), max_heap.end(), max_heap_comp ); max_heap.pop_back(); } } else { min_heap.push_back ( * iter ); push_heap ( min_heap.begin(), min_heap.end(), min_heap_comp ); if ( max_heap.size() + 1 < min_heap.size() ) { /* min_heap has got too large */ max_heap.push_back( min_heap.front() ); push_heap( max_heap.begin(), max_heap.end(), max_heap_comp ); pop_heap( min_heap.begin(), min_heap.end(), min_heap_comp ); min_heap.pop_back(); } } DEBUG( max_heap ); DEBUG( min_heap ); return min_heap.empty( ) /* corner case: ++first = last */ ? result_type ( *first, *first ) : result_type ( max_heap.size() < min_heap.size() ? min_heap.front() : max_heap.front(), min_heap.size() < max_heap.size() ? max_heap.front() : min_heap.front() ); } /* * geometry util * ---------------------------------------------- */ struct xyPoint { double x, y; xyPoint( const double & a = .0, const double & b = .0 ): x ( a ), y( b ) { }; }; struct xyCircle { xyPoint center; double radius; }; ostream & operator<< ( ostream & out, const xyPoint & p ) { out << '(' << p.x << ", " << p.y << ')'; return out; } istream & operator>> ( istream & ist, xyPoint & p ) { ist >> p.x >> p.y; return ist; } ostream & operator<< ( ostream & out, const xyCircle & o ) { out << "{(" << o.center.x << ", " << o.center.y << ") " << o.radius << '}'; return out; } istream & operator>> ( istream & ist, xyCircle & o ) { ist >> o.center.x >> o.center.y >> o.radius; return ist; } inline double cartesian_dist ( const xyPoint & a, const xyPoint & b ) { const double d = a.x - b.x; const double e = a.y - b.y; return sqrt ( d * d + e * e ); } class xyLine { public: xyLine ( const xyPoint & , const xyPoint & ); xyLine ( const double slope, const double intercept ); /* * 'signed' orthogonal distance; the sign is useful * to compare which side of the line the point is */ inline double orth_dist ( const xyPoint & ) const; private: double m_slope; double m_intercept; double m_normfac; /* normalization factor for orth_dist calc */ bool m_vertical; /* if the line is verticcal */ double m_xcross; /* x axis cross point for vertical line */ }; xyLine::xyLine ( const xyPoint & a, const xyPoint & b ) { if ( a.x == b.x ) /* vertical line */ { m_vertical = true; m_xcross = a.x; m_intercept = DOUBLE_NAN; m_slope = DOUBLE_INF; m_normfac = DOUBLE_NAN; } else { m_vertical = false; m_xcross = DOUBLE_NAN; m_slope = ( b.y - a.y ) / ( b.x - a.x ); m_intercept = a.y - m_slope * a.x; m_normfac = sqrt ( m_slope * m_slope + 1.0 ); } } xyLine::xyLine ( const double slope, const double intercept ): m_slope ( slope ), m_intercept ( intercept ) { m_vertical = false; m_xcross = DOUBLE_NAN; m_normfac = sqrt ( m_slope * m_slope + 1.0 ); } double xyLine::orth_dist ( const xyPoint & o ) const /* 'signed' orthogonal distance */ { if ( m_vertical ) return o.x - m_xcross; else return ( m_slope * o.x - o.y + m_intercept ) / m_normfac; } inline double triangle_area ( const xyPoint & a, const xyPoint & b, const xyPoint & c ) { const xyLine l ( a, b ); const double h = abs ( l.orth_dist ( c ) ); const double e = cartesian_dist ( a, b ); return h * e; } /* * operator<< overrides * ---------------------------------------------- */ namespace { /* helper function to output containers */ template < typename T > ostream & __output ( ostream & out, const T & a ) { typedef typename T::const_iterator const_iterator; out << "{ "; // does not work for 'pair' value type // copy ( a.begin( ), a.end( ), ostream_iterator < typename T::value_type > ( cout, ", " )); for ( const_iterator iter = a.begin(); iter != a.end(); ++ iter ) out << ( iter != a.begin() ? ", " : "" ) << *iter ; return out << " }"; } } template < typename key_type, typename value_type > ostream & operator<< ( ostream & out, const pair < key_type, value_type > & p) { out << "(" << p.first << ", " << p.second << ")"; return out; } template < typename T0, typename T1, typename T2 > ostream & operator<< ( ostream & out, const tuple < T0, T1, T2 > & t ) { out << "(" << get<0>(t) << ", " << get<1>(t) << ", " << get<2>(t) << ")"; return out; } template < typename T0, typename T1 > ostream & operator<< ( ostream & out, const tuple < T0, T1 > & t ) { out << "(" << get<0>(t) << ", " << get<1>(t) << ")"; return out; } template < typename key_type, typename value_type, typename comp > ostream & operator<< ( ostream & out, const map < key_type, value_type, comp > & m ) { return __output( out, m ); } template < typename value_type, typename comp > ostream & operator<< ( ostream & out, const set < value_type, comp > & s ) { return __output( out, s ); } template < typename value_type > ostream & operator<< ( ostream & out, const vector < value_type > & a ) { return __output( out, a ); } template < typename value_type > ostream & operator<< ( ostream & out, const list < value_type > & a ) { return __output( out, a ); } template < typename value_type > ostream & operator<< ( ostream & out, const vector < vector < value_type > > & a ) { typedef typename vector < vector < value_type > >::const_iterator const_iterator; for ( const_iterator iter = a.begin(); iter != a.end(); ++ iter ) out << '\n' << *iter ; return out; } /* * operator>> overrides * ---------------------------------------------- */ template < typename key_type, typename value_type > istream & operator>> ( istream & in, pair < key_type, value_type > & p) { in >> p.first >> p.second; return in; } template < typename T0, typename T1, typename T2 > istream & operator>> ( istream & fin, tuple < T0, T1, T2 > & t ) { fin >> get<0>(t) >> get<1>(t) >> get<2>(t); return fin; } template < typename value_type > istream & operator>> ( istream & in, vector < value_type > & a ) { typedef typename vector < value_type >::iterator iterator; if ( ! a.size( ) ) { size_t n; in >> n; a.resize( n ); } for ( iterator iter = a.begin(); iter != a.end(); ++ iter ) in >> * iter; return in; } /* * readin quick utilities * ---------------------------------------------- */ // template < typename value_type > // inline void readin ( vector < value_type > & a, size_t n = 0, istream & in = cin ) // { // // if ( ! n ) cin >> n; // if ( ! n ) in >> n ; // a.resize ( n ); // // cin >> a; // in >> a; // } // XXX consider removing // template < typename key_type, typename value_type > // inline void readin (vector < pair < key_type , value_type > > & a, size_t n = 0 ) // { // if ( !n ) cin >> n; // a.resize( n ); // cin >> a; // } /* * pair utility * ---------------------------------------------- */ namespace std { template<typename T1, typename T2> struct hash< std::pair< T1, T2 > > { inline size_t operator()( const std::pair< T1, T2 > & pr ) const { return fst(pr.first) ^ snd(pr.second); } const std::hash< T1 > fst; const std::hash< T2 > snd; }; } /* * accumulate ( m.begin( ), m.end( ), pair < int, double> ( 0 , 0.0 ) , operator+ < int, double > ); * stackoverflow.com/questions/18640152 */ template < typename T1, typename T2 > inline pair < T1, T2 > operator+ ( const pair < T1, T2 > & a, const pair < T1, T2 > & b ) { return make_pair < T1, T2 > ( a.first + b.first, a.second + b.second ); } template < typename T1, typename T2 > inline pair < T1, T2 > operator- ( const pair < T1, T2 > & a, const pair < T1, T2 > & b ) { return make_pair < T1, T2 > ( a.first - b.first, a.second - b.second ); } // template < class T1, class T2, class BinaryOperation > // class Apply2nd : binary_function < typename pair < T1, T2 >, // typename pair < T1, T2 >, // typename BinaryOperation::result_type > namespace { /*! * helper template to do the work */ template < size_t J, class T1, class T2 > struct Get; template < class T1, class T2 > struct Get < 0, T1, T2 > { typedef typename pair < T1, T2 >::first_type result_type; static result_type & elm ( pair < T1, T2 > & pr ) { return pr.first; } static const result_type & elm ( const pair < T1, T2 > & pr ) { return pr.first; } }; template < class T1, class T2 > struct Get < 1, T1, T2 > { typedef typename pair < T1, T2 >::second_type result_type; static result_type & elm ( pair < T1, T2 > & pr ) { return pr.second; } static const result_type & elm ( const pair < T1, T2 > & pr ) { return pr.second; } }; } template < size_t J, class T1, class T2 > typename Get< J, T1, T2 >::result_type & get ( pair< T1, T2 > & pr ) { return Get < J, T1, T2 >::elm( pr ); } template < size_t J, class T1, class T2 > const typename Get< J, T1, T2 >::result_type & get ( const pair< T1, T2 > & pr ) { return Get < J, T1, T2 >::elm( pr ); } /* * graph utils * ---------------------------------------------- */ /* maximum in sub-tree distance */ void get_indist( const size_t root, const vector < vector < size_t > > & tree, vector < tuple< size_t, size_t > > & indist ) { const auto NIL = numeric_limits< size_t >::max(); size_t a = 0, b = NIL; for ( const auto u: tree[ root ] ) { get_indist( u, tree, indist ); if ( a < 1 + get< 0 >( indist[ u ] ) ) { b = a; a = 1 + get< 0 >( indist[ u ] ); } else b = b != NIL ? max( b, 1 + get< 0 >( indist[ u ] )) : 1 + get< 0 >( indist[ u ] ); } indist[ root ] = make_tuple(a, b); } /* maximum out of subtree distance */ void get_outdist( const size_t root, const vector< vector< size_t > > & tree, const vector< tuple< size_t, size_t > > & indist, vector < size_t > & outdist ) { const auto NIL = numeric_limits< size_t >::max(); for( const auto u: tree[ root ] ) { if ( 1 + get< 0 >( indist[ u ] ) == get< 0 >( indist[ root ] ) ) outdist[ u ] = get< 1 >( indist[ root ] ) != NIL ? 1 + max( get< 1 >( indist[ root ] ), outdist[ root ] ) : 1 + outdist[ root ]; else outdist[ u ] = 1 + max( get< 0 >( indist[ root ] ), outdist[ root ] ); get_outdist( u, tree, indist, outdist ); } } /* * Dijkstra :: single-source shortest path problem for * a graph with non-negative edge path costs, producing * a shortest path tree * en.wikipedia.org/wiki/Dijkstra's_algorithm */ template < typename DistType > void Dijekstra ( const size_t & source, const vector < list < size_t > > & adj, // adjacency list const vector < vector < DistType > > & edge_len, // pair-wise distance for adjacent nodes vector < DistType > & dist, // distance from the source vector < size_t > prev ) // previous node in the shortest path tree { // TODO } // TODO http://en.wikipedia.org/wiki/Shortest_path_problem // TODO Graph class, Weighted graph, ... /* * maximum cardinality matching in a bipartite graph * G = G1 βˆͺ G2 βˆͺ {NIL} * where G1 and G2 are partition of graph and NIL is a special null vertex * https://en.wikipedia.org/wiki/Hopcroft-Karp_algorithm */ class HopcroftKarp { public: HopcroftKarp ( const vector < list < size_t > > & adj, const vector < bool > & tag ); size_t get_npair ( ) { return npair; }; map < size_t, size_t > get_map ( ); private: bool mf_breadth_first_search ( ); // breadth first search from unpaired nodes in G1 bool mf_depth_first_search ( const size_t v ); // dfs w/ toggeling augmenting paths const vector < list < size_t > > & m_adj; // adjacency list for each node const vector < bool > & m_tag; // binary tag distinguishing partitions size_t npair; const size_t NIL; // special null vertex const size_t INF; // practically infinity distance vector < size_t > m_g1; // set of nodes with tag = true vector < size_t > m_dist; // dist from unpaired vertices in G1 vector < size_t > m_pair; }; map < size_t, size_t > HopcroftKarp::get_map ( ) { map < size_t, size_t > m; for ( size_t j = 0; j < m_pair.size( ); ++ j ) if ( m_pair[ j ] != NIL && m_tag[ j ]) m[ j ] = m_pair[ j ]; return m; } HopcroftKarp::HopcroftKarp ( const vector < list < size_t > > & adj, const vector < bool > & tag ): m_adj ( adj ), m_tag ( tag ), npair ( 0 ), NIL ( adj.size( )), INF ( adj.size( ) + 1 ), m_dist ( vector < size_t > ( adj.size( ) + 1, INF)), m_pair ( vector < size_t > ( adj.size( ), NIL )) // initially everything is paired with nil { assert ( m_adj.size() == m_tag.size() ); for ( size_t j = 0; j < tag.size( ); ++ j ) if ( tag[ j ] ) m_g1.push_back ( j ); while ( mf_breadth_first_search ( ) ) for ( vector < size_t >::const_iterator v = m_g1.begin( ); v != m_g1.end( ); ++ v ) if ( m_pair[ *v ] == NIL && mf_depth_first_search ( *v ) ) ++ npair; } bool HopcroftKarp::mf_breadth_first_search( ) { /* only nodes from g1 are queued */ queue < size_t > bfs_queue; /* initialize queue with all unpaired nodes from g1 */ for ( vector < size_t >::const_iterator v = m_g1.begin( ); v != m_g1.end( ); ++v ) if ( m_pair[ *v ] == NIL ) { m_dist[ *v ] = 0; bfs_queue.push ( *v ); } else m_dist[ *v ] = INF; m_dist[ NIL ] = INF; /* find all the shortest augmenting paths to node nil */ while ( ! bfs_queue.empty() ) { const size_t v = bfs_queue.front( ); bfs_queue.pop ( ); if ( m_dist[ v ] < m_dist[ NIL ] ) for ( list < size_t >::const_iterator u = m_adj[ v ].begin( ); u != m_adj[ v ].end( ); ++ u ) if ( m_dist[ m_pair[ * u ] ] == INF ) { m_dist[ m_pair[ * u ] ] = m_dist[ v ] + 1; bfs_queue.push ( m_pair[ * u ] ); } } return m_dist[ NIL ] != INF; } bool HopcroftKarp::mf_depth_first_search( const size_t v ) { if ( v == NIL ) return true; else { for ( list < size_t >::const_iterator u = m_adj[ v ].begin( ); u != m_adj[ v ].end( ); ++ u ) if ( m_dist[ m_pair[ *u ] ] == m_dist[ v ] + 1 && mf_depth_first_search( m_pair[ *u ] )) { /* * there is an augmenting path to nil from m_pair[ *u ] * and hence there is an augmenting path from v to u and * u to to nil; therefore v and u can be paired together */ m_pair [ *u ] = v; m_pair [ v ] = *u; return true; } m_dist[ v ] = INF; return false; } } /** * lazy all pairs shortest path in a tree with only one BFS * test case: 'book of evil' * codeforces.com/problemset/problem/337/D */ class All_Pairs_Tree_Shortest_Path { public: All_Pairs_Tree_Shortest_Path( const vector< list < size_t > > & adj ): n( adj.size( ) ), depth( vector < size_t > ( n, All_Pairs_Tree_Shortest_Path::INF ) ), parent( vector < size_t > ( n ) ), dist( vector < vector < unsigned short > > ( n ) ) { /* perform bfs from root node '0' and assign depth to each node */ /* XXX probably would be worth to set the root as node with highest degree */ queue< size_t > bfs_queue; bfs_queue.push( 0 ); depth[ 0 ] = 0; parent[ 0 ] = 0; while ( ! bfs_queue.empty( ) ) { const size_t u = bfs_queue.front( ); bfs_queue.pop( ); for ( list< size_t >::const_iterator j = adj[ u ].begin( ); j != adj[ u ].end( ); ++ j ) if ( depth[ u ] + 1 < depth[ *j ] ) { depth[ *j ] = depth[ u ] + 1; parent[ *j ] = u; bfs_queue.push( *j ); } } /* adjust pair-wise distance to zero along the diagonal */ for ( size_t j = 1; j < n; ++ j ) dist[ j ].resize( j, All_Pairs_Tree_Shortest_Path::INF ); } /* interface object function as to lazily look-up distances */ size_t operator( )( const size_t u, const size_t v ) { if ( u == v ) return 0; else if ( u < v) return (*this)( v, u ); else if ( dist[ u ][ v ] == All_Pairs_Tree_Shortest_Path::INF ) { if ( depth[ u ] < depth[ v ] ) /* u is in a lower level than v */ dist[ u ][ v ] = 1 + (*this)( u, parent[ v ]); else if ( depth[ v ] < depth[ u ] ) /* v is in a lower level than u */ dist[ u ][ v ] = 1 + (*this)( parent[ u ], v ); else /* u and v are at the same depth */ dist[ u ][ v ] = 2 + (*this)( parent[ u ], parent[ v ] ); } return dist[ u ][ v ]; } /* TODO populate; a method which populates pair-wise distances * and returns the matrix */ private: /* * constant infinity value for initializing distances * even though this is private it will be assigned outside of the class */ static const unsigned short INF; const size_t n; /* numbert of nodes in the tree */ vector < size_t > depth; /* distance to root node '0' */ vector < size_t > parent; /* parent of each node with root node '0' */ vector < vector < unsigned short > > dist; /* pair-wise shortest path distance */ }; const unsigned short All_Pairs_Tree_Shortest_Path::INF = numeric_limits< unsigned short >::max( ); /* * data-structure utility * ---------------------------------------------- */ template < class T, class Comp = less< T > > class Heap /* less< T > --> max-heap */ { typedef T value_type; typedef typename vector < value_type >::size_type size_type; public: /* * stackoverflow.com/questions/10387751 * possible work-around: a memebr pointer to m_val * TODO static/friend heapify ( val, & heap ) XXX O( n ) ?! * TODO implement insert iterator */ Heap(): m_val( vector < value_type >() ), m_comp( Comp() ) {} Heap( const Comp & comp ): m_val( vector< value_type >() ), m_comp( comp ){ } template < class InputIter > Heap ( InputIter first, InputIter last, Comp comp=Comp() ): m_val ( vector < value_type > ( ) ), m_comp( comp ) { for ( ; first != last ; ++ first ) m_val.push_back ( * first ); make_heap( m_val.begin( ), m_val.end( ), m_comp ); } /*! * to avoid destroying heap property, front( ) * should always return a 'const' reference */ inline const value_type & front( ) const { return m_val.front( ); } inline bool empty( ) const { return m_val.empty( ); } inline size_type size( ) const { return m_val.size( ); } inline void push( const value_type & a ) { m_val.push_back( a ); push_heap( m_val.begin( ), m_val.end( ), m_comp ); } inline void pop( ) { pop_heap ( m_val.begin( ), m_val.end( ), m_comp ); m_val.pop_back( ); } // inline void swap( Heap< T, Comp> & other ) { m_val.swap( other.m_val ) }; // void sort( ) { sort_heap ( m_val.begin( ), m_val.end( ), m_comp ); } // template < class X, class Y > // friend ostream & operator<<( ostream & out, const Heap < X, Y> & heap ); private: vector < value_type > m_val; const Comp m_comp; }; /* * boost.org/doc/libs/1_54_0/libs/smart_ptr/shared_ptr.htm */ #if 1 < 0 template < class Type > class shared_ptr { typedef Type value_type; public: explicit shared_ptr ( value_type * p = NULL ) : ptr ( p ), count ( new size_t ( 1U ) ) { } shared_ptr ( const shared_ptr < value_type > & sp ): ptr ( sp.ptr ), count ( sp.count ) { ++ * count; } ~ shared_ptr ( ) { release( ); } bool operator== ( const shared_ptr < value_type > & sp ) { return ptr == sp.ptr; } bool operator!= ( const shared_ptr < value_type > & sp ) { return ptr != sp.ptr; } shared_ptr < value_type > & operator= ( const shared_ptr < value_type > & sp ) { if ( this != & sp && ptr != sp.ptr ) { release( ); ptr = sp.ptr; count = sp.count; ++ * count; } return * this; } value_type * operator-> ( ) { return ptr ; } value_type & operator* ( ) { return *ptr ; } const value_type * operator-> ( ) const { return ptr ; } const value_type & operator* ( ) const { return *ptr; } void swap ( shared_ptr < value_type > & sp ) { if ( this != &sp && ptr != sp.ptr ) { swap ( ptr, sp.ptr ); swap ( count, sp.count ); } } private: void release ( ) { /* stackoverflow.com/questions/615355 */ -- * count; if ( ! * count ) { delete count; delete ptr; count = NULL; ptr = NULL; } } value_type * ptr; size_t * count; }; #endif /*! * union find data structure with * - lazy unions * - union by rank * - path compression */ class UnionFind { public: UnionFind( const size_t n ): parent ( vector < size_t > ( n ) ), /* initialize each node as its own */ rank ( vector < size_t > ( n, 0 )) /* parent and set all the ranks to 0 */ { for ( size_t j = 0; j < n; ++ j ) parent[ j ] = j ; } inline size_t find( const size_t s ) { /* * perform path compresion and add shortcut * if parent[ s ] is not a root node */ const size_t p = parent[ s ]; return parent[ p ] == p ? p : parent[ s ] = find( p ) ; } inline void lazy_union ( size_t i, size_t j ) { /* unions should be done on root nodes */ i = find( i ); j = find( j ); if ( i != j ) { if ( rank [ i ] < rank[ j ] ) parent[ i ] = j; else { parent[ j ] = i; rank[ i ] += rank[ i ] == rank[ j ]; } } } private: vector < size_t > parent; vector < size_t > rank; }; // TODO XXX // template < class NumType > // unsigned num_hash_func ( const NumType & a ) // { // // XXX what will happen in case of overflow? // return static_cast < unsigned > ( a % 9973 ) % 9973 ; // } /* * XXX: HashMap: map< Key, T > data [ 9973 ] * data [ num_hash_func ( key ) ][ key ] */ /* * testing util * ---------------------------------------------- */ // TODO add a preprocessor which automatically includes the funciton name, or __line__ // and disables if not in debug mode /* prints the life length of the object when it goes out of scope */ class ScopeTimer { public: ScopeTimer ( const string & msg = "" ): tic ( clock ( )), m_msg( msg ) { }; ~ ScopeTimer ( ) { const clock_t toc = clock(); const uint64 dt = 1000L * ( toc - tic ) / CLOCKS_PER_SEC; const uint64 mil = dt % 1000L; const uint64 sec = ( dt / 1000L ) % 60L; const uint64 min = ( dt / 60000L ) % 60L; const uint64 hrs = ( dt / 3600000L ); cout << '\n' << m_msg << "\n\telapsed time: "; if ( hrs ) cout << hrs << " hrs, "; if ( min ) cout << min << " min, "; if ( sec ) cout << sec << " sec, "; cout << mil << " mil-sec\n"; } private: typedef unsigned long long int uint64; const clock_t tic; const string m_msg; }; class RandInt { public: RandInt ( int a = 0, int b = 100 ): m ( a ), f ( static_cast < double > ( b - a ) / RAND_MAX ) { } inline int operator() ( ) { return m + ceil ( f * rand( ) ); } private: const int m; const double f; }; class RandDouble { public: RandDouble ( double a = 0.0, double b = 1.0 ): m ( a ), f ( ( b - a ) / RAND_MAX ) { } inline double operator() ( ) { return m + f * rand( ); } private: const double m, f; }; class Noisy { public: Noisy( string str ): msg ( str ) { cout << " Noisy ( " << msg << " )\t@ " << this << endl; } ~Noisy() { cout << "~Noisy ( " << msg << " )\t@ " << this << endl; } void beep() { cout << " beep ( " << msg << " )\t@ " << this << endl; } void beep() const { cout << " const beep ( " << msg << " )\t@ " << this << endl; } private: const string msg; }; // DECLARE ( Noisy ); /* * -- @@@ ------------------------------------------------- */ tuple< double, double, double > get_line_coef( const pair< double, double > & a, const pair< double, double > & b ) { if( a.first != b.first ) { const auto slope = (b.second - a.second) / (b.first - a.first); const auto intercept = a.second - slope * a.first; return make_tuple( slope, -1.0, intercept ); } else // vertical line return make_tuple( 1.0, 0.0, - a.first ); } inline pair< double, double > cross( const tuple< double, double, double > & fst, const tuple< double, double, double > & snd ) { const auto a1 = get< 0 >( fst ); const auto b1 = get< 1 >( fst ); const auto c1 = get< 2 >( fst ); const auto a2 = get< 0 >( snd ); const auto b2 = get< 1 >( snd ); const auto c2 = get< 2 >( snd ); if( a2 != 0 ) { const auto y = (- c1 + a1 / a2 * c2) / ( b1 - a1 / a2 * b2 ); const auto x = - ( b2 * y + c2 ) / a2; return make_pair( x, y ); } const auto x = ( - c1 + b1 / b2 * c2 ) / ( a1 - b1 / b2 * a2 ); const auto y = - ( a2 * x + c2 ) / b2; return make_pair( x, y ); } inline double dist2d( const pair< double, double > & a, const pair< double, double > & b ) { const auto x = a.first - b.first; const auto y = a.second - b.second; return x * x + y * y; } inline bool iscross( const double abdist, const double adist, const double bdist ) { return max(adist, bdist) < abdist; } size_t probA() { pair< double, double > a, b; cin >> a >> b; const auto l = get_line_coef(a, b); const auto abdist = dist2d( a, b ); DEBUG( l ); DEBUG( abdist ); vector< tuple< double, double, double > > line; cin >> line; const auto n = line.size(); size_t val = 0; for( size_t i = 0; i < n; ++ i ) { // call with the second line const auto p = cross( l, line[ i ] ); const auto adist = dist2d( a, p ); const auto bdist = dist2d( b, p ); DEBUG( p ); DEBUG( iscross( abdist, adist, bdist ) ); val += iscross( abdist, adist, bdist ); } return val; } int main(const int argc, char * argv []) { cout << probA(); //cout << setprecision( 12 ); return EXIT_SUCCESS; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:256000000") using namespace std; const double infd = 2e+9; const int infi = (1 << 30) - 1; const long long infl = (1ll << 60) - 1; const int mod = 1e+9 + 7; template <class T> inline T sqr(T x) { return x * x; } struct pt { int x, y; static pt get() { pt a; cin >> a.x >> a.y; return a; } }; struct line { int a, b, c; static line get() { line l; cin >> l.a >> l.b >> l.c; return l; } bool ro(pt p) { long long res = a * 1ll * p.x + b * 1ll * p.y + c; return res > 0; } }; int main() { pt a = pt::get(); pt b = pt::get(); int n; cin >> n; int result = 0; for (int i = 0; i < n; i++) { line l = line::get(); bool x = l.ro(a); bool y = l.ro(b); if (x != y) result++; } cout << result; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.io.*; import java.util.*; public class problem499C { public static void main (String[]args) throws IOException{ BufferedReader x=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(x.readLine()); long x1=Long.parseLong(st.nextToken()); long y1=Long.parseLong(st.nextToken()); st=new StringTokenizer(x.readLine()); long x2=Long.parseLong(st.nextToken()); long y2=Long.parseLong(st.nextToken()); long n=Long.parseLong(x.readLine()); long count=0; for (int i=0; i<n; i++){ st=new StringTokenizer(x.readLine()); long a=Long.parseLong(st.nextToken()); long b=Long.parseLong(st.nextToken()); long c=Long.parseLong(st.nextToken()); if (x1*a+y1*b+c>0 ^ x2*a+y2*b+c>0)count++; } System.out.println(count); } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; int main() { long long n, X1, Y1, X2, Y2, a, b, c; while (cin >> X1 >> Y1) { cin >> X2 >> Y2; cin >> n; vector<int> V1, V2; for (int i = 0; i < n; i++) { cin >> a >> b >> c; if (a * X1 + b * Y1 + c > 0) V1.push_back(1); else V1.push_back(0); if (a * X2 + b * Y2 + c > 0) V2.push_back(1); else V2.push_back(0); } int ans = 0; for (int i = 0; i < n; i++) if (V1[i] != V2[i]) ans++; cout << ans << endl; } }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
h1, h2 = list(map(int,input().split())) u1, u2 = list(map(int,input().split())) pasos = 0 for i in int(input())*'_': a, b, c= list(map(int,input().split())) if (a * h1 + b * h2 + c) * (a * u1 + b * u2 + c) < 0: pasos+=1 print(pasos)
PYTHON3
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
from __future__ import division home = map(int, raw_input().split()) univ = map(int, raw_input().split()) n = input() roads = [map(int, raw_input().split()) for _ in xrange(n)] def isacross(a, b, c): home_val = a * home[0] + b * home[1] + c univ_val = a * univ[0] + b * univ[1] + c return ((home_val < 0 and univ_val > 0) or (home_val > 0 and univ_val < 0)) ans = 0 for i in roads: if isacross(*i): ans += 1 print ans
PYTHON
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.util.Scanner; import java.util.TreeMap; public class ProblemE { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); double xh = scanner.nextDouble(), yh = scanner.nextDouble(), xu = scanner.nextDouble(), yu = scanner.nextDouble(); int n = scanner.nextInt(); int rest = 0; for(int i = 0; i < n; i++){ double a = scanner.nextDouble(), b = scanner.nextDouble(), c = scanner.nextDouble(); if(b != 0){ double y1 = (-a*xh - c) / b; double y2 = (-a*xu - c) / b; if((y1 < yh && y2 > yu) || (y1 > yh && y2 < yu) ){ rest++; } } else { if( a != 0){ double x1 = (-b*yh - c) / a; double x2 = (-b*yu - c) / a; if((x1 < xh && x2 > xu) || (x1 > xh && x2 < xu) ){ rest++; } } } } System.out.println(rest); } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; bool bet(double val, double a, double b) { return (val >= a && val <= b) || (val >= b && val <= a); } struct line { double a, b, c; long long x1, x2, y1, y2; line(long long _x1, long long _y1, long long _x2, long long _y2) { x1 = _x1, y1 = _y1, x2 = _x2, y2 = _y2; if (x1 == x2) { b = 0, a = 1, c = -x1; } else { b = 1; a = -(double)(y1 - y2) / (x1 - x2); c = -a * x1 - b * y1; } } line(int _a, int _b, int _c) { a = _a, b = _b, c = _c; if (b != 0) { a /= b; c /= b; b = 1; } } bool intersect(line l) { if (fabs(l.a - a) < 1e-6 && fabs(l.b - b) < 1e-6) return false; double xx, yy; xx = (l.c * b - c * l.b) / (l.b * a - l.a * b); if (l.b == 0) yy = -a * xx - c; else yy = -l.a * xx - l.c; return online(xx, yy); } bool online(double xx, double yy) { return bet(xx, x1, x2) && bet(yy, y1, y2); } }; int main() { int sx, sy, ex, ey; scanf("%d %d %d %d", &sx, &sy, &ex, &ey); line seg(sx, sy, ex, ey); int n, a, b, c; cin >> n; int cnt = 0; for (int i = 0; i < n; i++) { cin >> a >> b >> c; if (seg.intersect(line(a, b, c))) cnt++; } cout << cnt; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
x1, y1 = map(int, input().split()) x2, y2 = map(int, input().split()) n = int(input()) num_sign_diff = 0 for road in range(n): a, b, c = map(int, input().split()) pos1 = (a * x1 + b * y1 + c) > 0 pos2 = (a * x2 + b * y2 + c) > 0 if pos1 + pos2 == 1: #exactly one of them is on positive side of line num_sign_diff += 1 print(num_sign_diff)
PYTHON3
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; struct Point { long long x; long long y; }; struct Vector { long long x; long long y; Vector(long long a, long long b) { x = a; y = b; } Vector(Point A, Point B) { x = B.x - A.x; y = B.y - A.y; } }; int sign(long long a) { if (a > 0) return +1; if (a == 0) return 0; if (a < 0) return -1; } int crossproduct(Vector a, Vector b) { return a.x * b.y - a.y * b.x; } int main() { cout.precision(7); cout << fixed; int n; Point A, B; cin >> A.x >> A.y >> B.x >> B.y; cin >> n; int a[n], b[n], c[n]; for (int i = 0; i < n; i++) { cin >> a[i] >> b[i] >> c[i]; } int anw = 0; for (int i = 0; i < n; i++) { if (sign(a[i] * A.x + b[i] * A.y + c[i]) * sign(a[i] * B.x + b[i] * B.y + c[i]) < 0) anw++; } cout << anw; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.io.*; import java.util.StringTokenizer; public class Main { static MyScanner in; static PrintWriter out; //static Timer t = new Timer(); public static void main(String[] args) throws IOException { in = new MyScanner(); out = new PrintWriter(System.out, true); long x1 = in.nextInt(), y1 = in.nextInt(); long x2 = in.nextInt(), y2 = in.nextInt(); int n = in.nextInt(); int cnt = 0; for(long i = 0; i < n; i++) { long a = in.nextInt(); long b = in.nextInt(); long c = in.nextInt(); long l1 = a * x1 + b * y1 + c; long l2 = a * x2 + b * y2 + c; if(l1 < 0 && l2 > 0 || l1 > 0 && l2 < 0) cnt++; } out.println(cnt); } } //<editor-fold defaultstate="collapsed" desc="MyScanner"> class MyScanner { private final BufferedReader br; private StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public MyScanner(File f) throws FileNotFoundException { br = new BufferedReader(new FileReader(f)); } public MyScanner(String path) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(path))); } String next() throws IOException { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() { if(st != null && st.hasMoreElements()) return true; try { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); } catch(Exception e) { return false; } return true; } String nextLine() throws IOException { return br.readLine(); } String[] nextStrings(int n) throws IOException { String[] arr = new String[n]; for(int i = 0; i < n; i++) arr[i] = next(); return arr; } String[] nextLines(int n) throws IOException { String[] arr = new String[n]; for(int i = 0; i < n; i++) arr[i] = nextLine(); return arr; } int nextInt() throws IOException { return Integer.parseInt(next()); } int[] nextInts(int n) throws IOException { int[] arr = new int[n]; for(int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } int[][] next2Ints(int n, int m) throws IOException { int[][] arr = new int[n][m]; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) arr[i][j] = nextInt(); return arr; } long nextLong() throws IOException { return Long.parseLong(next()); } long[] nextLongs(int n) throws IOException { long[] arr = new long[n]; for(int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } long[][] next2Longs(int n, int m) throws IOException { long[][] arr = new long[n][m]; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) arr[i][j] = nextLong(); return arr; } double nextDouble(boolean replace) throws IOException { if(replace) return Double.parseDouble(next().replace(',', '.')); else return Double.parseDouble(next()); } boolean nextBool() throws IOException { String s = next(); if(s.equalsIgnoreCase("true") || s.equals("1")) return true; if(s.equalsIgnoreCase("false") || s.equals("0")) return false; throw new IOException("Boolean expected, String found!"); } } //</editor-fold>
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
/* PROB: Main LANG: JAVA */ import java.io.*; import java.util.*; import java.awt.geom.Line2D; public class Main{ final double LRG = 100001.0; void run() throws Exception { long x1 = nextLong(), y1 = nextLong(), x2 = nextLong(), y2 = nextLong(); int N = nextInt(); int cnt = 0; for(int i = 0; i < N; i++){ long a = nextLong(), b = nextLong(), c = nextLong(); long p1 = a*x1 + b*y1 + c; long p2 = a*x2 + b*y2 + c; if(p1 > 0 ^ p2 > 0) cnt++; } out.println(cnt); } public static void main(String args[]) throws Exception { new Main().run(); } BufferedReader in; PrintStream out; StringTokenizer st; Main() throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); out = System.out; } Main(String is, String os) throws Exception { in = new BufferedReader(new FileReader(new File(is))); out = new PrintStream(new File(os)); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } } class Debug{ static String err(String s){ System.out.println(s); return s; } static int[][] err(int[][] arr){ for(int i =0; i < arr.length; i++){ for(int j = 0; j < arr[0].length; j++){ System.out.printf("%4d", arr[i][j]); } System.out.println(); } return arr; } static void err(int b, int blen){ String s = Integer.toString(b, 2); while(s.length() < blen) s = "0" + s; System.out.println(s); } static int err(int a){ System.out.println(a); return a; } } //simple point class for geometry class Point{ double x; double y; public Point(double px, double py){ x = px; y = py; } public String toString(){ return "(" + x + ", " + y + ")"; } public boolean equals(Point p2){ return x == p2.x && y == p2.y; } public double getDist(Point p2){ return Math.sqrt((x - p2.x)* (x - p2.x) + (y - p2.y)*(y - p2.y)); } public static int ccw(Point a, Point b, Point 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; } } class Line{ Point p1; Point p2; public Line(double x1, double y1, double x2, double y2){ p1 = new Point(x1, y1); p2 = new Point(x2, y2); } public Line(Point p1t, Point p2t){ p1 = p1t; p2 = p2t; } public boolean contains(Point p){ double dx = p2.x - p.x; double dy = p2.y - p.y; double ldx = p.x - p1.x; double ldy = p.y - p1.y; return (in(p.x, p1.x, p2.x) && in(p.y, p1.y, p2.y) && dx*ldy == dy*ldx); } public boolean intersects(Line l){ Line2D me = new Line2D.Double(p1.x, p1.y, p2.x, p2.y); Line2D u = new Line2D.Double(l.p1.x, l.p1.y, l.p2.x, l.p2.y); return me.intersectsLine(u); } public boolean in(double t, double a, double b){ return (t >= Math.min(a, b) && t <= Math.max(a, b)); } public String toString(){ return p1 + " -----> " + p2; } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; const int MAXN = 2e6 + 5; const long long MOD = 1e9 + 7; struct Line { double a, b, c; }; int main() { pair<double, double> home, univ; cin >> home.first >> home.second; cin >> univ.first >> univ.second; int n; cin >> n; vector<Line> v(n); int ans = 0; for (int i = 0; i < n; ++i) { cin >> v[i].a >> v[i].b >> v[i].c; if ((v[i].a * home.first + v[i].b * home.second + v[i].c) * (v[i].a * univ.first + v[i].b * univ.second + v[i].c) < 0) { ans++; } } cout << ans; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
if __name__ == '__main__': xhome, yhome = [int(x) for x in input().split()] xuni, yuni = [int(x) for x in input().split()] n_roads = int(input()) n_steps = 0 for i in range(n_roads): a, b, c = [int(x) for x in input().split()] hline = (a*xhome) + (b*yhome) + c uline = (a*xuni) + (b*yuni) + c if hline * uline < 0: n_steps += 1 print(n_steps)
PYTHON3
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; map<string, string> cc; int n; int main() { long long x1, y1, x2, y2; while (scanf("%I64d%I64d", &x1, &y1) == 2) { scanf("%I64d%I64d", &x2, &y2); scanf("%d", &n); long long a, b, c, ans = 0; for (int i = 0; i < n; ++i) { scanf("%I64d%I64d%I64d", &a, &b, &c); long long d1 = a * x1 + b * y1 + c; long long d2 = a * x2 + b * y2 + c; if ((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) ans++; } printf("%I64d\n", ans); } return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long x, y; long long a, b; cin >> x >> y; cin >> a >> b; long long n; cin >> n; long long ans = 0ll; long long k, l, m; for (long long i = 0ll; i < n; ++i) { cin >> k >> l >> m; if ((((k * x + l * y + m) / abs(k * x + l * y + m)) * ((k * a + l * b + m) / abs(k * a + l * b + m))) < 0ll) ans++; } cout << ans << endl; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { long x1=in.nextLong(),y1=in.nextLong(); long x2=in.nextLong(),y2=in.nextLong(); int n=(int)in.nextLong(); int ans=0; for(int i=0;i<n;i++){ long a=in.nextLong(),b=in.nextLong(),c=in.nextLong(); long val1=a*x1+b*y1+c; long val2=a*x2+b*y2+c; val1=val1/Math.abs(val1); val2=val2/Math.abs(val2); if(val1*val2<0) ans++; } out.printLine(ans); } } class InputReader { BufferedReader in; StringTokenizer tokenizer=null; public InputReader(InputStream inputStream) { in=new BufferedReader(new InputStreamReader(inputStream)); } public String next() { try{ while (tokenizer==null||!tokenizer.hasMoreTokens()) { tokenizer=new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } catch (IOException e) { return null; } } public long nextLong() { return Long.parseLong(next()); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:1000000000") using namespace std; const bool db = false; int n; double a[100010], b[100010], c[100010]; double sx, sy, fx, fy; set<pair<double, double> > in; pair<double, double> intr(double A1, double B1, double C1, double A2, double B2, double C2) { if (abs(A1 * B2 - B1 * A2) < 1e-9) { return make_pair(-1000000007, -1000000007); } double det = A1 * B2 - B1 * A2; double detx = C1 * B2 - B1 * C2; double dety = A1 * C2 - C1 * A2; return make_pair(-detx / det, -dety / det); } int main() { cin >> sx >> sy >> fx >> fy; cin >> n; for (int i = 1; i <= n; ++i) { cin >> a[i] >> b[i] >> c[i]; double D = sqrt(a[i] * a[i] + b[i] * b[i]); a[i] /= D; b[i] /= D; c[i] /= D; } double la = fy - sy; double lb = sx - fx; double lc = sy * fx - fy * sx; double D = sqrt(la * la + lb * lb); la /= D; lb /= D; lc /= D; int ans = 0; for (int i = 1; i <= n; ++i) { pair<double, double> G = intr(a[i], b[i], c[i], la, lb, lc); if (G == make_pair(-1000000007 * 1.0, -1000000007 * 1.0)) continue; double dt = (fx != sx ? 1.0 * (G.first - sx) / (fx - sx) : (G.second - sy) / (fy - sy)); if (dt > 0 && dt < 1) ++ans; } cout << ans << endl; getchar(); getchar(); return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
x,y = map(int,input().split()) p,q = map(int,input().split()) n = int(input()) k = 0 for i in range(n): a,b,c = map(int,input().split()) if (((a*x)+(b*y)+(c))*((a*p)+(b*q)+c))<0 : k+=1 print(k)
PYTHON3
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; int n; long long x2, x3, y2, y3; int main() { cin >> x3 >> y3 >> x2 >> y2; scanf("%d", &n); int ans = 0; for (int i = 1; i <= n; i++) { long long a, b, c; cin >> a >> b >> c; long long res1, res2; res1 = a * x2 + b * y2 + c; res2 = a * x3 + b * y3 + c; if ((res1 > 0) != (res2 > 0)) ans++; } printf("%d\n", ans); return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.util.*; import java.io.*; public class cf { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); long x1 = sc.nextInt(), y1 = sc.nextInt(); long x2 = sc.nextInt(), y2 = sc.nextInt(); int k = 0; int n = sc.nextInt(); for (int i = 0; i < n; i++) { long a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt(); if (a * x1 + b * y1 + c > 0 ^ a * x2 + b * y2 + c > 0) { k++; } } pw.println(k); pw.close(); } static PrintWriter pw = new PrintWriter(System.out); public static class pair implements Comparable<pair> { long x; long y; public pair(long x, long y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Double(x).hashCode() * 31 + new Double(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextInt(); return arr; } public Integer[] nextsort(int n) throws IOException { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public boolean ready() throws IOException { return br.ready(); } } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.io.IOException; import java.util.Hashtable; import java.util.InputMismatchException; import java.util.Scanner; public class cf284_c { public static long A1,B1,A2,B2; public static void main(String args[]){ Scanner s=new Scanner(System.in); A1=s.nextLong(); B1=s.nextLong(); A2=s.nextLong(); B2=s.nextLong(); Hashtable<Double, Integer> table=new Hashtable<Double, Integer>(); int n=s.nextInt(); long count=0; while(n-->0) { long a1=s.nextLong(); long a2=s.nextLong(); long a3=s.nextLong(); double t=intersects(a1, a2, a3); // System.out.println(t); if(t>=0) count++;//table.put(t, 0); } System.out.println(count); } public static double intersects(long a1,long b1,long c1) { long x=a1*(A1-A2)+b1*(B1-B2); if(x==0) return -1; double y=a1*A1+b1*B1+c1; double t=y/x; if(t>=0 && t<=1) return t; return -1; } public static class FastScanner { 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 = System.in.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 int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; long long sx, sy, ex, ey; int n; int main() { cin >> sx >> sy; cin >> ex >> ey; cin >> n; int ans = 0; while (n--) { long long a, b, c; cin >> a >> b >> c; int f1 = (sx * a + sy * b + c) > 0 ? 1 : 0; int f2 = (ex * a + ey * b + c) > 0 ? 1 : 0; if (f1 != f2) { ans++; } } cout << ans << endl; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; long long a, b, c, d; long long N, A, B, C; int ans = 0; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> a >> b >> c >> d; cin >> N; for (int i = 0; i < N; i++) { cin >> A >> B >> C; long long x = a * A + b * B + C; long long y = c * A + d * B + C; if ((x > 0 && y < 0) || (x < 0 && y > 0)) ans++; } cout << ans << endl; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; inline long long MIN(long long a, long long b) { return a > b ? b : a; } inline long long MAX(long long a, long long b) { return a > b ? a : b; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); long long arr[2][2]; for (long long i = 0; i < 2; i++) { for (long long j = 0; j < 2; j++) { cin >> arr[i][j]; } } long long n; cin >> n; long long v[3], ans = 0; for (long long i = 0; i < n; i++) { for (long long j = 0; j < 3; j++) { cin >> v[j]; } long long val1 = v[0] * arr[0][0] + v[1] * arr[0][1] + v[2]; long long val2 = v[0] * arr[1][0] + v[1] * arr[1][1] + v[2]; if ((val1 < 0 && val2 > 0) || (val1 > 0 && val2 < 0)) { ans++; } } cout << ans << "\n"; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
x1,y1=map(int,input().split()) x2,y2=map(int,input().split()) n=int(input()) summa=0 for i in range(n): a,b,c=map(int,input().split()) if (a*x1+b*y1+c)*(a*x2+b*y2+c)<0: summa+=1 print(summa)
PYTHON3
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.swing.text.html.Option; /** * @author grozhd */ public class Geometry { static Point home; static Point uni; static List<Line> lines; public static void main(String[] args) { read(); double leftEnd = Math.min(uni.x, home.x); double rightEnd = Math.max(uni.x, home.x); double botEnd = Math.min(uni.y, home.y); double upEnd = Math.max(uni.y, home.y); int result = 0; Line path = new Line(home, uni); for (Line line : lines) { final Optional<Point> intersection = path.intersect(line); if (intersection.isPresent() && intersection.get().x >= leftEnd && intersection.get().x <= rightEnd && intersection.get().y >= botEnd && intersection.get().y <= upEnd ) { result++; } } System.out.println(result); } private static class Point { double x; double y; public Point(double x, double y) { this.x = x; this.y = y; } } private static class Line { double a; double b; double c; public Line(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } public Line(Point p1, Point p2) { if (p1.x == p2.x) { a = 1.; b = 0.; c = - p1.x; } else if (p1.y == p2.y) { a = 0.; b = 1.; c = -p1.y; } else { a = 1.; b = (p1.x - p2.x) / (p2.y - p1.y); c = - p1.x - b * p1.y; } } public Optional<Point> intersect(Line o) { double x; double y; if (b == 0) { if (o.b == 0) { return Optional.empty(); } x = - c / a; y = (- o.c - o.a * x) / o.b; return Optional.of(new Point(x, y)); } else if (o.b == 0) { return o.intersect(this); } else if (a / b == o.a / o.b) { return Optional.empty(); } x = (c * (o.b / b) - o.c) / (o.a - a * (o.b / b)); y = (- c - a * x) / b; return Optional.of(new Point(x, y)); } } private static List<Integer> read() { List<Integer> result = new ArrayList<Integer>(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); final String[] s1 = reader.readLine().split(" "); home = new Point(Integer.parseInt(s1[0]), Integer.parseInt(s1[1])); final String[] s2 = reader.readLine().split(" "); uni = new Point(Integer.parseInt(s2[0]), Integer.parseInt(s2[1])); int n = Integer.parseInt(reader.readLine()); lines = new ArrayList<>(n); for (int i = 0; i < n; i++) { String[] s = reader.readLine().split(" "); lines.add(new Line(Integer.parseInt(s[0]), Integer.parseInt(s[1]), Integer.parseInt(s[2]))); } } catch (Exception e) { } return result; } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 7; const int N = 1e6 + 5; long long gcd(long long a, long long b) { if (!b) return a; return gcd(b, a % b); } int max(int a, int b) { return a > b ? a : b; } template <typename T> T min(T a, T b) { return a < b ? a : b; } vector<vector<long long>> makeMatrix(int r, int c) { vector<vector<long long>> m; m.resize(r); for (int i = 0; i < int(r); ++i) m[i] = vector<long long>(c, 0); return m; } int MOD; void printMatrix(const vector<vector<long long>>& m) { for (int i = 0; i < int(m.size()); ++i) { for (int j = 0; j < int(m[0].size()); ++j) cout << m[i][j] << " "; cout << endl; } } vector<vector<long long>> operator*(const vector<vector<long long>>& m1, const vector<vector<long long>>& m2) { vector<vector<long long>> tmp = makeMatrix(m1.size(), m2[0].size()); for (int i = 0; i < int(m1.size()); ++i) { for (int j = 0; j < int(m1[0].size()); ++j) { for (int k = 0; k < int(m2[0].size()); ++k) { tmp[i][k] = (tmp[i][k] + m1[i][j] * m2[j][k]) % MOD; } } } return tmp; } vector<vector<long long>> modpow(vector<vector<long long>> b, long long e) { if (!e) { vector<vector<long long>> m = makeMatrix(b.size(), b[0].size()); for (int i = 0; i < int(::min(m.size(), m[0].size())); ++i) m[i][i] = 1; return m; } if (e & 1) return b * modpow(b, e - 1); b = modpow(b, e / 2); return b * b; } long long euler(long long n) { long long res = n; for (long long PF = 2; PF * PF <= n; ++PF) { if (n % PF == 0) { while (n % PF == 0) n /= PF; res = res * (PF - 1) / PF; } } if (n != 1) res = res * (n - 1) / n; return res; } int main() { long long x1, x2, y1, y2, n, a, b, c, r = 0, x, y; cin >> x1 >> y1 >> x2 >> y2; cin >> n; for (int i = 0; i < int(n); ++i) { cin >> a >> b >> c; x = (a * x1 + b * y1 + c); y = (a * x2 + b * y2 + c); if (x < 0 && y > 0 || y < 0 && x > 0) ++r; } cout << r << endl; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; int n; long long a, b, c, xs, ys, xe, ye; int cnt; int main() { cin >> xs >> ys; cin >> xe >> ye; scanf("%d", &n); while (n--) { cin >> a >> b >> c; if (!((a * xs + b * ys > -c && a * xe + b * ye > -c) || (a * xs + b * ys < -c && a * xe + b * ye < -c))) cnt++; } cout << cnt << endl; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#import sys #sys.stdin = open('input.txt', 'r') #sys.stdout = open('output.txt', 'w') def norm(a, b, c, d): if (b * c >= 0): return a * abs(c) <= abs(b) <= d * abs(c) return -a * abs(c) >= abs(b) >= -d * abs(c) x1, y1 = map(int, input().split()) x2, y2 = map(int, input().split()) a2 = y2 - y1 b2 = x1 - x2 c2 = 0 - a2 * x1 - b2 * y1 n = int(input()) ans = 0 for i in range(n): a1, b1, c1 = map(int, input().split()) if (norm(min(x1, x2), (c2 * b1 - c1 * b2), (a1 * b2 - a2 * b1), max(x1, x2)) and norm(min(y1, y2), (c2 * a1 - c1 * a2), (a2 * b1 - a1 * b2), max(y1, y2))): ans += 1 print(ans)
PYTHON3
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> int sx, sy, ex, ey; int N, A[333], B[333], C[333]; long long D[333], E[333]; int main() { int i, j, k; scanf("%d%d%d%d%d", &sx, &sy, &ex, &ey, &N); for (i = 1; i <= N; i++) scanf("%d%d%d", A + i, B + i, C + i); for (i = 1; i <= N; i++) { D[i] = (long long)A[i] * sx + (long long)B[i] * sy + C[i]; E[i] = (long long)A[i] * ex + (long long)B[i] * ey + C[i]; if (D[i] > 0) D[i] = 1; else D[i] = -1; if (E[i] > 0) E[i] = 1; else E[i] = -1; } int ans = 0; for (i = 1; i <= N; i++) if (D[i] * E[i] < 0) ans++; printf("%d\n", ans); }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class C { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(bf.readLine()); int x1 = Integer.parseInt(st.nextToken()); int y1 = Integer.parseInt(st.nextToken()); st = new StringTokenizer(bf.readLine()); int x2 = Integer.parseInt(st.nextToken()); int y2 = Integer.parseInt(st.nextToken()); int n = Integer.parseInt(bf.readLine()); int counter = 0; for(int i=0; i<n; i++) { st = new StringTokenizer(bf.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int c = Integer.parseInt(st.nextToken()); long val1 = 1L*a*x1 + 1L*b*y1 + c; long val2 = 1L*a*x2 + 1L*b*y2 + c; if(val1 > 0 && val2 < 0 || val1 < 0 && val2 > 0) counter++; } System.out.println(counter); // Scanner scan = new Scanner(System.in); // PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); // int n = Integer.parseInt(bf.readLine()); // StringTokenizer st = new StringTokenizer(bf.readLine()); // int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken()); // int n = Integer.parseInt(st.nextToken()); // int n = scan.nextInt(); // out.close(); System.exit(0); } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int x1 = in.nextInt(); int y1 = in.nextInt(); int x2 = in.nextInt(); int y2 = in.nextInt(); int n = in.nextInt(); int ans = 0; for (int i = 0; i < n; i++) { long a = in.nextInt(); long b = in.nextInt(); long c = in.nextInt(); long p1 = a * x1 + b * y1 + c; long p2 = a * x2 + b * y2 + c; if ((p1 > 0 && p2 < 0) || (p2 > 0 && p1 < 0)) { ans++; } } out.println(ans); } } static class InputReader { private StringTokenizer tokenizer; private BufferedReader reader; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private void fillTokenizer() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } } public String next() { fillTokenizer(); return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
h1,h2=input().split() u1,u2=input().split() h1,h2=int(h1),int(h2) u1,u2=int(u1),int(u2) n=int(input()) lis=[] for i in range(n): lis.append(input().split()) for i in range(n): for j in range(3): lis[i][j]=int(lis[i][j]) def status(a,b,lis): if a*lis[0]+b*lis[1]+lis[2]>0: return 1 else: return 0 c=0 for i in range(n): if status(h1,h2,lis[i])!=status(u1,u2,lis[i]): c+=1 print(c)
PYTHON3
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
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.StringTokenizer; public class ExtendedEuclid { static final double EPS = 1e-9; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); Point a = new Point(sc.nextDouble(), sc.nextDouble()); Point b = new Point(sc.nextDouble(), sc.nextDouble()); int n = sc.nextInt(); Line[] l = new Line[n]; for (int i = 0; i < n; i++) { l[i] = new Line(sc.nextDouble(), sc.nextDouble(), sc.nextDouble()); } int c = 0; for (int i = 0; i < n; i++) { // System.out.println(l[i].ccw(a)); // System.out.println(l[i].ccw(b)); double x=l[i].a*a.x +l[i].b*a.y+l[i].c; double y=l[i].a*b.x +l[i].b*b.y+l[i].c; if ((x+EPS>0 && y<0+EPS) ||(y+EPS>0 && x<0+EPS) ) c++; } System.out.println(c); pw.flush(); } 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 Line { static final double INF = 1e9, EPS = 1e-9; double a, b, c; Point p, q; Line(double x, double y, double z) { a = x; b = y; c = z; if (b == 0) { p = new Point(-c, 0); q = new Point(-c, 1); } else if(a==0) { p = new Point(0, -c); q = new Point(1, -c); }else { p = new Point(-c / a, 0); q = new Point((-c - b) / a, 1); } } Line(Point p, Point q) { this.p = p; this.q = 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 ccw(Point r) { return new Vector(p, q).cross(new Vector(p, r))+EPS > 0; } 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 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; } 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); } Point reflectionPoint(Line l) // reflection point of p on line l { Point p = l.closestPoint(this); Vector v = new Vector(this, p); return this.translate(v).translate(v); } 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); } // Another way: find closest point and calculate the distance between it and p static double distToLineSegment(Point p, Point a, Point b) { Vector ap = new Vector(a, p), ab = new Vector(a, b); double u = ap.dot(ab) / ab.norm2(); if (u < 0.0) return p.dist(a); if (u > 1.0) return p.dist(b); return distToLine(p, a, b); } // Another way: find closest point and calculate the distance between it and p } 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 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
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.util.*; import java.io.*; import java.math.*; public class Class{ public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int x1 = Integer.parseInt(st.nextToken()); int y1 = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int x2 = Integer.parseInt(st.nextToken()); int y2 = Integer.parseInt(st.nextToken()); int n = Integer.parseInt(br.readLine()); int sum = 0; for(int i=0; i<n; i++){ st = new StringTokenizer(br.readLine()); long a = Long.parseLong(st.nextToken()); long b = Long.parseLong(st.nextToken()); long c = Long.parseLong(st.nextToken()); if((a*x1+b*y1+c)>0&&(a*x2+b*y2+c)<0)sum++; else if((a*x1+b*y1+c)<0&&(a*x2+b*y2+c)>0)sum++; } System.out.print(sum); } static class Pair{ long start; long end; public Pair(long start, long end){ this.start = start; this.end = end; } public int hashCode() { return (int)(this.start + this.end); } public boolean equals(Object p){ if(((Pair)p).start==this.start && ((Pair)p).end==this.end)return true; return false; } } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> const long long mod = 1e9 + 7; const long long INF = 9 * 1e18; using namespace std; void solve() { long long sx, sy, hx, hy, n, ans = 0, a, b, c; cin >> sx >> sy; cin >> hx >> hy; cin >> n; while (n--) { cin >> a >> b >> c; long long flag1 = 0, flag2 = 0; flag1 = a * sx + b * sy + c; if (flag1 >= 0) flag1 = 1; else flag1 = 2; flag2 = a * hx + b * hy + c; if (flag2 >= 0) flag2 = 1; else flag2 = 2; if (flag1 != flag2) ans++; } cout << ans << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); long long q = 1; while (q--) { solve(); } return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class CrazyTown { public static BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); public static StringTokenizer st; public static void main(String[] args) throws IOException { int x1 = nextInt(); int y1 = nextInt(); int x2 = nextInt(); int y2 = nextInt(); int n = nextInt(); int count = 0; for (int i = 0; i < n; i++) { int a = nextInt(); int b = nextInt(); int c = nextInt(); boolean u = f(x1, y1, a, b, c); boolean v = f(x2, y2, a, b, c); if (u != v) count++; } System.out.println(count); } public static boolean f(long x, long y, long a, long b, long c) { return a*x + b*y + c > 0; } public static String nextLine() throws IOException { return f.readLine(); } public static String nextString() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(f.readLine()); return st.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(nextString()); } public static long nextLong() throws IOException { return Long.parseLong(nextString()); } public static int[] intArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public static int[][] intArray(int n, int m) throws IOException { int[][] a = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = nextInt(); return a; } public static long[] longArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } }
JAVA
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; const int inf = 1e9; const long long INF = 1e18; const double PI = acos(-1.0); const double EPS = 1e-8; const int MOD = 1000000007; struct Point { int x, y; Point() {} Point(int x, int y) : x(x), y(y) {} }; struct Line { int a, b, c; Line() {} Line(int a, int b, int c) : a(a), b(b), c(c) {} int Orientation(Point p) { long long int val = 1LL * a * p.x + 1LL * b * p.y + c; if (val == 0) return 0; if (val > 0) return 1; else return -1; } } L; vector<Line> V; int main(int argc, char const *argv[]) { ios_base::sync_with_stdio(false); cin.tie(NULL); Point a, b; cin >> a.x >> a.y >> b.x >> b.y; int n; cin >> n; for (int i = 1; i <= n; i++) { int a, b, c; cin >> a >> b >> c; V.push_back(Line(a, b, c)); } int ans = 0; for (auto x : V) { int X = x.Orientation(a); int Y = x.Orientation(b); if (X != Y) ans++; } cout << ans << endl; return 0; }
CPP
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
import java.io.*; import java.util.*; public class Solution{ static int mod=1000000007; public static void main(String[] args){ long x1 = longg(); long y1 = longg(); long x2 = longg(); long y2 = longg(); int n = intt(); int ans=0; for(int i=1;i<=n;i++){ long a=longg(); long b=longg(); long c=longg(); long val1 = a*x1+b*y1+c; long val2 = a*x2+b*y2+c; if((val1<0&&val2>0)||(val1>0&&val2<0)) ans++; } System.out.println(ans); } static FastReader sc=new FastReader(); static PrintWriter out = new PrintWriter(System.out); static int intt(){ int x = sc.nextInt(); return(x); } static long longg(){ long x = sc.nextLong(); return(x); } static double doublee(){ double t = sc.nextDouble(); return(t); } static String str(){ String s = sc.next(); return(s); } static String strln(){ String s = sc.nextLine(); return(s); } static long pow(long a,long b){ long ans=1; while(b>0){ if(b%2==1) ans=(ans*a); a=(a*a)%mod; b=b/2; } return(ans); } static long GCD(long a,long b){ if(b%a==0) return(a); return(GCD(b%a,a)); } static long LCM(long a,long b){ return ((a*b)/GCD(a,b)); } static long abs(long x,long y) { return(Math.abs(x-y));} static long min(long x,long y){ return(Math.min(x,y)); } static long max(long a,long b){ return Math.max(a,b); } static long Fermat(long a,long p){ long b = p-2,ans=1; while(b>0){ if(b%2==1) ans=(ans*a)%p; a=(a*a)%p; b=b/2; } return(ans); } static void Fact(long a[],long m){ a[0]=1; for(int i=1;i<a.length;i++) a[i]=(i*a[i-1])%m; } static void Fact_Inv(long a[],long F[],long m){ int n =a.length; a[n-1]=Fermat(F[n-1],m); for(int i=n-2;i>=0;i--) a[i]=((i+1)*a[i+1])%m; } /*static long d, x, y; static void extendedEuclid(long A, long B) { if(B == 0) { d = A; x = 1; y = 0; } else { extendedEuclid(B, A%B); long temp = x; x = y; y = temp - (A/B)*y; } } */ /*static class pair implements Comparable<pair>{ int x,y; pair(int a,int b){ x=a; y=b; } public int compareTo(pair p1) { return((p1.x-p1.y)-(this.x-this.y));} public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; pair other = (pair) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } @Override public int hashCode() { return(x-y); } } */ 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
498_A. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≀ x1, y1 ≀ 106) β€” the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≀ x2, y2 ≀ 106) β€” the coordinates of the university you are studying at. The third line contains an integer n (1 ≀ n ≀ 300) β€” the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≀ ai, bi, ci ≀ 106; |ai| + |bi| > 0) β€” the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image>
2
7
#include <bits/stdc++.h> using namespace std; int main() { long long xa, ya, xb, yb; cin >> xa >> ya >> xb >> yb; long long n, a, b, c, ch = 0; cin >> n; for (long long i = 0; i < n; i++) { cin >> a >> b >> c; if ((a * xa + b * ya + c > 0 && a * xb + b * yb + c < 0) || (a * xa + b * ya + c < 0 && a * xb + b * yb + c > 0)) ch++; } cout << ch; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 5; const int mod = 1e9 + 9; map<pair<int, int>, int> mp; pair<int, int> p[MAXN]; set<int> st; int num[MAXN]; long long fast_pow(long long x, int n) { long long ret = 1; while (n) { if (n & 1) { ret = ret * x % mod; } x = x * x % mod; n >>= 1; } return ret; } bool check(int k) { int x = p[k].first, y = p[k].second; for (int i = -1; i < 2; ++i) { int tmp = mp[pair<int, int>(x + i, y + 1)]; if (tmp && num[tmp] == 1) return false; } return true; } void add(int k) { int x = p[k].first, y = p[k].second; for (int i = -1; i < 2; ++i) { int tmp = mp[pair<int, int>(x + i, y - 1)]; if (tmp && ~num[tmp] && check(tmp)) { st.insert(tmp); } } } void change(int k) { int x = p[k].first, y = p[k].second; for (int i = -1; i < 2; ++i) { int tmp = mp[pair<int, int>(x + i, y - 1)]; if (tmp && ~num[tmp]) { set<int>::iterator it = st.lower_bound(tmp); if (*it == tmp) { st.erase(it); } } } } int main() { int n; while (~scanf("%d", &n)) { long long ans = 0; mp.clear(); for (int i = 1; i <= n; ++i) { num[i] = 0; scanf("%d%d", &p[i].first, &p[i].second); mp[pair<int, int>(p[i].first, p[i].second)] = i; } for (int i = 1; i <= n; ++i) { int x = p[i].first, y = p[i].second; for (int j = -1; j < 2; ++j) { int tmp = mp[pair<int, int>(x + j, y + 1)]; if (tmp) { ++num[tmp]; } } } for (int i = 1; i <= n; ++i) { if (check(i)) { st.insert(i); } } int turn = 0, now = n - 1; while (!st.empty()) { set<int>::iterator it = turn ? st.begin() : --st.end(); int m = *it; ans = (ans + (m - 1) * fast_pow(n, now--) % mod) % mod; num[m] = -1; int x = p[m].first, y = p[m].second; st.erase(it); for (int i = -1; i < 2; ++i) { int tmp = mp[pair<int, int>(x + i, y + 1)]; if (tmp && ~num[tmp] && --num[tmp] == 1) { change(tmp); } } add(m); turn ^= 1; } printf("%I64d\n", ans); } return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; struct cube { long long ind, dl, dr, dd; }; vector<long long> sol, p; set<pair<long long, long long> > s; set<long long> canget; map<pair<long long, long long>, long long> goind; map<long long, pair<long long, long long> > gocoord; pair<long long, long long> t; vector<cube> v; void pows(long long n) { p.push_back(1); for (long long i = 0; i < 1000000; ++i) p.push_back((p[i] * n) % (1000 * 1000 * 1000 + 9)); } bool can_I_get_a_cube(long long i) { pair<long long, long long> poz = gocoord[i]; pair<long long, long long> uu = make_pair(poz.first, poz.second + 1), ul = make_pair(poz.first - 1, poz.second + 1), ur = make_pair(poz.first + 1, poz.second + 1); pair<long long, long long> l = make_pair(poz.first - 1, poz.second), ll = make_pair(poz.first - 2, poz.second), r = make_pair(poz.first + 1, poz.second), rr = make_pair(poz.first + 2, poz.second); if ((!s.count(l) && !s.count(ll) && s.count(ul)) || (!s.count(r) && !s.count(rr) && s.count(ur)) || (!s.count(l) && !s.count(r) && s.count(uu))) return false; return true; } void pizdim(long long i) { pair<long long, long long> poz = gocoord[i]; s.erase(s.find(poz)); canget.erase(canget.find(i)); pair<long long, long long> dd = make_pair(poz.first, poz.second - 1), dl = make_pair(poz.first - 1, poz.second - 1), dr = make_pair(poz.first + 1, poz.second - 1); pair<long long, long long> l = make_pair(poz.first - 1, poz.second), ll = make_pair(poz.first - 2, poz.second), r = make_pair(poz.first + 1, poz.second), rr = make_pair(poz.first + 2, poz.second); if (s.count(l) && !can_I_get_a_cube(goind[l]) && canget.count(goind[l])) canget.erase(canget.find(goind[l])); if (s.count(r) && !can_I_get_a_cube(goind[r]) && canget.count(goind[r])) canget.erase(canget.find(goind[r])); if (s.count(ll) && !can_I_get_a_cube(goind[ll]) && canget.count(goind[ll])) canget.erase(canget.find(goind[ll])); if (s.count(rr) && !can_I_get_a_cube(goind[rr]) && canget.count(goind[rr])) canget.erase(canget.find(goind[rr])); if (s.count(dd) && can_I_get_a_cube(goind[dd])) canget.insert(goind[dd]); if (s.count(dl) && can_I_get_a_cube(goind[dl])) canget.insert(goind[dl]); if (s.count(dr) && can_I_get_a_cube(goind[dr])) canget.insert(goind[dr]); sol.push_back(i); } int main() { ios_base::sync_with_stdio(false); long long n; cin >> n; for (long long i = 0; i < n; ++i) { cin >> t.first >> t.second; t.first += (1000 * 1000 * 1000 + 9) + (1000 * 1000 * 1000 + 9); t.second += (1000 * 1000 * 1000 + 9) + (1000 * 1000 * 1000 + 9); s.insert(t); gocoord[i] = t; goind[t] = i; } for (long long i = 0; i < n; ++i) if (can_I_get_a_cube(i)) canget.insert(i); pows(n); for (long long i = 0; i < n; ++i) if (!(i % 2)) pizdim(*(--canget.end())); else pizdim(*canget.begin()); long long x = 0; for (long long i = 0; i < n; ++i) { x += sol[i] * p[n - i - 1]; x %= (1000 * 1000 * 1000 + 9); } cout << x; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
import java.awt.geom.*; import java.io.*; import java.math.*; import java.util.*; import java.util.regex.*; import static java.lang.Math.*; public class B { public static final int MOD = 1000000009; long D = 1000000001; boolean invalid(Map<Long, Integer> map, long p) { long x = p/D; long y = p%D; boolean a = map.containsKey((x-2)*D+y); boolean b = map.containsKey((x-1)*D+y); boolean c = map.containsKey((x+1)*D+y); boolean d = map.containsKey((x+2)*D+y); boolean e = map.containsKey((x-1)*D+y+1); boolean f = map.containsKey((x)*D+y+1); boolean g = map.containsKey((x+1)*D+y+1); return e&&!(a||b) || f&&!(b||c) || g&&!(c||d); } public B() throws Exception { int n = in.nextInt(); Map<Long, Integer> map = new HashMap<>(); TreeSet<Long> set = new TreeSet<>((a, b) -> map.get(a) - map.get(b)); for (int i=0; i<n; i++) { int x = in.nextInt() + 1000000001; int y = in.nextInt(); long p = x*D + y; map.put(p, i); set.add(p); } List<Integer> list = new ArrayList<Integer>(); for (int i=0; !set.isEmpty(); i^=1) { if (i==0) { while (true) { long p = set.pollLast(); if (!invalid(map, p)) { list.add(map.remove(p)); long x = p/D; long y = p%D; if (map.containsKey((x-1)*D+y-1)) set.add((x-1)*D+y-1); if (map.containsKey((x)*D+y-1)) set.add((x)*D+y-1); if (map.containsKey((x+1)*D+y-1)) set.add((x+1)*D+y-1); break; } } } else { while (true) { long p = set.pollFirst(); if (!invalid(map, p)) { list.add(map.remove(p)); long x = p/D; long y = p%D; if (map.containsKey((x-1)*D+y-1)) set.add((x-1)*D+y-1); if (map.containsKey((x)*D+y-1)) set.add((x)*D+y-1); if (map.containsKey((x+1)*D+y-1)) set.add((x+1)*D+y-1); break; } } } } long ans = list.get(0); for (int i=1; i<n; i++) { ans = (ans * n + list.get(i)) % MOD; } buf.append(ans).append('\n'); } public static Scanner in = new Scanner(System.in); public static StringBuilder buf = new StringBuilder(); public static void debug(Object... arr) { // {{{ System.err.println(Arrays.deepToString(arr)); } // }}} public static void main(String[] args) throws Exception { // {{{ new B(); System.out.print(buf); } // }}} public static class Scanner { // {{{ BufferedReader br; String line; StringTokenizer st; public Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public boolean hasNext() throws IOException { while ((st==null||!st.hasMoreTokens())&&(line=br.readLine())!=null) st = new StringTokenizer(line); return st.hasMoreTokens(); } public String next() throws IOException { if (hasNext()) return st.nextToken(); throw new NoSuchElementException(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } // }}} }
JAVA
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; const int N = 100500; const int MOD = (int)1e9 + 9; int add(int a, int b) { a += b; if (a >= MOD) a -= MOD; return a; } int mul(int a, int b) { long long c = (long long)a * b; return (int)(c % MOD); } int n; pair<int, int> cube[N]; map<pair<int, int>, int> cube_to_ind; set<int> candidates; int res[N]; pair<int, int> add(pair<int, int> c, int dx, int dy) { return make_pair(c.first + dx, c.second + dy); } int has(pair<int, int> c) { return cube_to_ind.count(c); } bool is_stable(pair<int, int> c) { if (has(c) == 0) return true; if (c.second == 0) return true; int cnt = has(add(c, -1, -1)) + has(add(c, 0, -1)) + has(add(c, 1, -1)); return cnt > 1; } void try_take(pair<int, int> c) { auto it = cube_to_ind.find(c); if (it == cube_to_ind.end()) return; int ind = it->second; if (is_stable(add(c, -1, 1)) && is_stable(add(c, 0, 1)) && is_stable(add(c, 1, 1))) { candidates.insert(ind); } else { candidates.erase(ind); } } void solve() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d%d", &cube[i].first, &cube[i].second); for (int i = 0; i < n; i++) cube_to_ind[cube[i]] = i; for (int i = 0; i < n; i++) try_take(cube[i]); for (int i = 0; !candidates.empty(); i++) { int ind; if (i % 2 == 0) { ind = *prev(candidates.end()); candidates.erase(prev(candidates.end())); } else { ind = *candidates.begin(); candidates.erase(candidates.begin()); } res[i] = ind; auto c = cube[ind]; cube_to_ind.erase(c); try_take(add(c, -1, -1)); try_take(add(c, 0, -1)); try_take(add(c, 1, -1)); try_take(add(c, -1, 0)); try_take(add(c, 1, 0)); try_take(add(c, -2, 0)); try_take(add(c, 2, 0)); } int ans = 0; for (int i = 0; i < n; i++) ans = add(mul(ans, n), res[i]); printf("%d\n", ans); } int main() { solve(); 0; return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; const int N = 1e5; const long long M = 1e9 + 9; int n, x, y; pair<int, int> pos[N]; map<pair<int, int>, int> mp; set<int> q; long long ans; int children(int x, int y) { int ret = 0; for (int dx = -1; dx <= 1; dx++) { map<pair<int, int>, int>::iterator c = mp.find(make_pair(x + dx, y - 1)); if (c != mp.end()) ret++; } return ret; } void update(int x, int y) { map<pair<int, int>, int>::iterator p = mp.find(make_pair(x, y)); if (p == mp.end()) return; for (int dx = -1; dx <= 1; dx++) { map<pair<int, int>, int>::iterator c = mp.find(make_pair(x + dx, y + 1)); if (c != mp.end() && children(x + dx, y + 1) == 1) { q.erase(p->second); return; } } q.insert(p->second); } void insert(int x, int y, int z) { pos[z].first = x; pos[z].second = y; mp[make_pair(x, y)] = z; } void remove(int x, int y) { mp.erase(make_pair(x, y)); for (int dx = -1; dx <= 1; dx++) { update(x + dx, y + 1); update(x + dx, y - 1); } for (int dx = -2; dx <= 2; dx++) { update(x + dx, y); } } int main() { cin >> n; for (int i = 0; i < n; i++) { cin >> x >> y; insert(x, y, i); } for (int i = 0; i < n; i++) { update(pos[i].first, pos[i].second); } for (int act = 0; !q.empty(); act++) { set<int>::iterator it; if ((act & 1) == 0) { it = --q.end(); } else { it = q.begin(); } ans = ans * n + (*it); ans %= M; remove(pos[*it].first, pos[*it].second); q.erase(it); } cout << ans; return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; int n; long long ans; set<int> s; map<pair<int, int>, int> mp; pair<int, int> pos[100005]; inline int cnt(int x, int y) { int res = 0; for (int i = -1; i <= 1; i++) if (mp[make_pair(x + i, y - 1)] != 0) res++; return res; } inline bool can_ins(int t) { int x = pos[t].first; int y = pos[t].second; for (int j = -1; j <= 1; j++) if (mp[make_pair(x + j, y + 1)] != 0 && cnt(x + j, y + 1) == 1) return false; return true; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { int x, y; scanf("%d%d", &x, &y); mp[make_pair(x, y)] = i; pos[i] = make_pair(x, y); } for (int i = 1; i <= n; i++) if (can_ins(i)) s.insert(i); for (int ii = 1; ii <= n; ii++) { int t; if (ii % 2) t = *s.rbegin(); else t = *s.begin(); s.erase(t); int x = pos[t].first; int y = pos[t].second; mp[pos[t]] = 0; for (int j = -2; j <= 2; j++) for (int k = -1; k <= 0; k++) { int id = mp[make_pair(x + j, y + k)]; if (id == 0) continue; s.erase(id); if (can_ins(id)) s.insert(id); } ans = ans * (long long)n + (long long)(t - 1); ans = ans % 1000000009; } cout << ans; return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; const int MAX = 1e5 + 5; const int MOD = 1e9 + 9; set<pair<int, int> > Q[2]; pair<int, int> idd[MAX]; map<pair<int, int>, int> id; vector<int> lista; int dx[] = {-2, -1, 0, 1, 2, -2, -1, 1, 2, -2, -1, 0, 1, 2}; int dy[] = {-1, -1, -1, -1, -1, 0, 0, 0, 0, 1, 1, 1, 1, 1}; int abajo(int idx) { int ans = 0; pair<int, int> p = idd[idx], q; for (int i = -1; i <= 1; i++) { q = make_pair(p.first + i, p.second - 1); if (id.count(q)) ans++; } return ans; } bool impos(int idx) { pair<int, int> p = idd[idx], q; for (int i = -1; i <= 1; i++) { q = make_pair(p.first + i, p.second + 1); if (!id.count(q)) continue; if (abajo(id[q]) == 1) return 1; } return 0; } int main() { int n, a, b; cin >> n; for (int i = 0; i < (int)(n); i++) { cin >> a >> b; idd[i] = make_pair(a, b); id[idd[i]] = i; } for (int i = 0; i < (int)(n); i++) { int aux = impos(i); Q[1].insert(make_pair(aux, i)); Q[0].insert(make_pair(aux, -i)); } int play = 0, idx, flag; pair<int, int> p, q, coor, aux, node; while (!Q[0].empty()) { p = *Q[play].begin(); q = make_pair(p.first, -p.second); lista.push_back(abs(p.second)); Q[play].erase(p); Q[1 - play].erase(q); coor = idd[abs(p.second)]; id.erase(idd[abs(p.second)]); for (int k = 0; k < (int)(14); k++) { aux = make_pair(coor.first + dx[k], coor.second + dy[k]); if (!id.count(aux)) continue; idx = id[aux]; flag = impos(idx); node = make_pair(1 - flag, idx); if (Q[1].count(node)) { Q[1].erase(node); Q[1].insert(make_pair(flag, idx)); } node = make_pair(1 - flag, -idx); if (Q[0].count(node)) { Q[0].erase(node); Q[0].insert(make_pair(flag, -idx)); } } play = 1 - play; } long long ans = 0; for (int i = 0; i < (int)(lista.size()); i++) { ans = (n * ans + lista[i]) % MOD; } cout << ans << endl; return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; const long long INF = 1 << 28; const long long LINF = 1ll << 61; const long long mod = 1e9 + 9; inline int getval() { int __res = 0; bool __neg = 0; char __c; __c = getchar(); while (__c == ' ' || __c == '\n') __c = getchar(); while (__c != ' ' && __c != '\n') { if (__c == '-') __neg = 1; else __res = __res * 10 + __c - '0'; __c = getchar(); } if (__neg) __res = -__res; return __res; } set<int> s; int m; bool used[100111], imp[100111]; int cntup[100111], cntdown[100111]; pair<int, int> p[100111]; map<pair<int, int>, int> pos; void update1(int t) { imp[t] = 0; for (int i = -1; i <= 1; i++) { int y = pos[make_pair(p[t].first + i, p[t].second + 1)]; if (y != 0 && !used[y] && cntdown[y] == 1) { imp[t] = 1; if (s.find(t) != s.end()) s.erase(t); return; } } if (!imp[t]) s.insert(t); } void update2(int t) { for (int i = -1; i <= 1; i++) { int y = pos[make_pair(p[t].first + i, p[t].second - 1)]; if (y != 0 && !used[y]) { imp[y] = 1; if (s.find(y) != s.end()) s.erase(y); break; } } } void remove(int t) { used[t] = 1; for (int i = -1; i <= 1; i++) { int y = pos[make_pair(p[t].first + i, p[t].second - 1)]; if (y != 0 && !used[y]) { cntup[y]--; update1(y); } } for (int i = -1; i <= 1; i++) { int y = pos[make_pair(p[t].first + i, p[t].second + 1)]; if (y != 0 && !used[y]) { cntdown[y]--; if (cntdown[y] == 1) update2(y); } } } int main() { m = getval(); for (int i = 1; i <= m; i++) { p[i].first = getval(), p[i].second = getval(); pos[p[i]] = i; } for (int x = 1; x <= m; x++) { for (int i = -1; i <= 1; i++) { int y = pos[make_pair(p[x].first + i, p[x].second + 1)]; if (y != 0) cntup[x]++, cntdown[y]++; } } for (int x = 1; x <= m; x++) { for (int i = -1; i <= 1; i++) { int y = pos[make_pair(p[x].first + i, p[x].second + 1)]; if (cntdown[y] == 1) imp[x] = 1; } if (!imp[x]) s.insert(x); } long long ans = 0; for (int i = 1; i <= m; i++) { int t; if (i & 1) t = *(--s.end()), s.erase(--s.end()); else t = *s.begin(), s.erase(s.begin()); ans = (ans * m + t - 1) % mod; remove(t); } printf("%I64d\n", ans); return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; struct point { int x, y; int id; bool operator<(const point &b) const { if (y == b.y) return x < b.x; return y < b.y; } }; set<point> points_coord; vector<point> points; set<int> available; bool is_available(point &p) { point aux = p; aux.y++; if (points_coord.find(aux) != points_coord.end()) { bool ok = false; aux.y--; aux.x--; if (points_coord.find(aux) != points_coord.end()) ok = true; aux.x += 2; if (points_coord.find(aux) != points_coord.end()) ok = true; if (!ok) return false; } aux = p; aux.y++; aux.x++; if (points_coord.find(aux) != points_coord.end()) { bool ok = false; aux.y--; if (points_coord.find(aux) != points_coord.end()) ok = true; aux.x++; if (points_coord.find(aux) != points_coord.end()) ok = true; if (!ok) return false; } aux = p; aux.y++; aux.x--; if (points_coord.find(aux) != points_coord.end()) { bool ok = false; aux.y--; if (points_coord.find(aux) != points_coord.end()) ok = true; aux.x--; if (points_coord.find(aux) != points_coord.end()) ok = true; if (!ok) return false; } return true; } long long to_number(int n, int vid, long long ans) { ans = (ans * n) % 1000000009; return (ans + vid) % 1000000009; } int main() { int n; cin >> n; for (int i = 0; i < n; i++) { point p; cin >> p.x >> p.y; p.id = i; points.push_back(p); points_coord.insert(p); } for (int i = 0; i < n; i++) { if (is_available(points[i])) { available.insert(i); } } bool play = false; long long ans = 0; while (!available.empty()) { set<int>::iterator id = (!play ? available.end() : available.begin()); if (!play) id--; int vid = *id; available.erase(id); points_coord.erase(points[vid]); ans = to_number(n, vid, ans); point aux = points[vid]; for (int i = 0; i < 2; i++) { aux.x--; if (!is_available(aux)) { set<point>::iterator x = points_coord.find(aux); if (x != points_coord.end()) { available.erase(x->id); } } } aux = points[vid]; for (int i = 0; i < 2; i++) { aux.x++; if (!is_available(aux)) { set<point>::iterator x = points_coord.find(aux); if (x != points_coord.end()) { available.erase(x->id); } } } aux = points[vid]; aux.y--; aux.x++; for (int i = 0; i < 3; i++) { if (is_available(aux)) { set<point>::iterator x = points_coord.find(aux); if (x != points_coord.end()) { available.insert(x->id); } } aux.x--; } play = !play; } cout << ans << endl; return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; map<long long, int> MAP; long long MOD = 1e9 + 9; vector<pair<int, int> > inp; const int MAX = 1e5 + 5; set<int> FREE; int dx[3] = {-1, 0, +1}; int dy[3] = {-1, -1, -1}; int ONLY[MAX], depend[MAX]; void check(int id) { int cnt = 0, only; for (int i = 0; i < 3; i++) { int x = inp[id].first + dx[i], y = inp[id].second + dy[i]; long long hash = MOD * x + y; if (MAP.count(hash) == 0) continue; int val = MAP[hash]; cnt++; only = val; } if (cnt == 1) { FREE.erase(only); ONLY[id] = only; depend[only]++; } } int main() { set<int> store; vector<int> ans; int n; cin >> n; for (int i = 0; i < n; i++) { int a, b; scanf("%d %d", &a, &b); inp.push_back(pair<int, int>(a, b)); MAP[MOD * a + b] = i; FREE.insert(i); } memset(ONLY, -1, sizeof ONLY); for (int i = 0; i < n; i++) check(i); int turn = 0; while (FREE.size()) { int x = 0, y = 0, id; if (turn == 0) { set<int>::iterator it = FREE.end(); it--; id = *it; } else id = *FREE.begin(); x = inp[id].first, y = inp[id].second; MAP.erase(MOD * x + y); FREE.erase(id); ans.push_back(id); if (ONLY[id] != -1) { int r = ONLY[id]; depend[r]--; if (depend[r] == 0) FREE.insert(r); } if (MAP.count(MOD * (x - 1) + (y + 1))) check(MAP[MOD * (x - 1) + (y + 1)]); if (MAP.count(MOD * (x) + (y + 1))) check(MAP[MOD * (x) + (y + 1)]); if (MAP.count(MOD * (x + 1) + (y + 1))) check(MAP[MOD * (x + 1) + (y + 1)]); turn = turn ^ 1; } long long pw = 1, yolo = 0; reverse(ans.begin(), ans.end()); for (int i = 0; i < ans.size(); i++) { long long here = (long long)ans[i] * pw; here %= MOD; yolo += here; pw = (pw * n) % MOD; if (yolo >= MOD) yolo -= MOD; } cout << yolo << endl; return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; map<pair<int, int>, int> mapa; set<int> S; vector<int> E[200000], I[200000]; int n; int X[200000], Y[200000]; int grau[200000]; vector<int> ans; int ja[200000]; void update(int i) { if (ja[i]) return; int mn = 2; for (int j = 0; j < E[i].size(); j++) { int viz = E[i][j]; if (ja[viz]) continue; if (mn = min(mn, grau[viz])) ; } if (mn == 0) exit(-1); if (mn != 1) S.insert(i); else if (S.find(i) != S.end()) S.erase(S.find(i)); } int main() { cin >> n; for (int i = 0; i < n; i++) { int x, y; cin >> x >> y; pair<int, int> p = pair<int, int>(x, y); X[i] = x, Y[i] = y; mapa[p] = i; } for (int i = 0; i < n; i++) { for (int d = -1; d < 2; d++) { pair<int, int> p = pair<int, int>(X[i] + d, Y[i] + 1); if (mapa.find(p) != mapa.end()) { int id = mapa[p]; E[i].push_back(id); I[id].push_back(i); grau[id]++; } } } for (int i = 0; i < n; i++) { int mn = 2; for (int j = 0; j < E[i].size(); j++) { int viz = E[i][j]; if (mn = min(mn, grau[viz])) ; } if (mn != 1) S.insert(i); } int cur = 0; while (S.size() > 0) { cur ^= 1; int v; set<int>::iterator it; if (cur) { it = S.end(); it--; v = *it; S.erase(it); } else { it = S.begin(); v = *it; S.erase(it); } ans.push_back(v); ja[v] = 1; for (int i = 0; i < I[v].size(); i++) { update(I[v][i]); } for (int i = 0; i < E[v].size(); i++) { int viz = E[v][i]; if (ja[viz]) continue; grau[viz]--; if (grau[viz] == 1) { for (int j = 0; j < I[viz].size(); j++) { int viz2 = I[viz][j]; if (viz2 == v) continue; update(viz2); } } } } long long ans2 = 0; long long mul = 1; for (int i = ans.size() - 1; i >= 0; i--) { ans2 += (long long)ans[i] * mul; ans2 %= 1000000009; mul *= n; mul %= 1000000009; } cout << ans2 << endl; return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; const int P = 1e9 + 9; const int N = 1e5 + 5; int n; int xx[N], yy[N]; map<pair<int, int>, int> cube; int isdanger[N], num[N], tree[N * 4]; int gett(pair<int, int> x) { if (cube.count(x)) return cube[x]; else return -1; } void add(int k, int m, int n, int x, int s) { if (m > x || n < x) return; if (m == n) { tree[k] = s; return; } int mid = m + n >> 1, z1 = k << 1, z2 = z1 + 1; add(z1, m, mid, x, s); add(z2, mid + 1, n, x, s); tree[k] = tree[z1] + tree[z2]; } int find(int k, int m, int n, int mark) { if (m == n) return m; int mid = m + n >> 1, z1 = k << 1, z2 = z1 + 1; if ((tree[z2] && mark == 0) || (tree[z1] == 0 && mark == 1)) return find(z2, mid + 1, n, mark); else return find(z1, m, mid, mark); } void modify(int x, int s) { if (x == -1) return; if (num[x] == 0 && s > 0) { add(1, 0, n - 1, x, 0); } if (num[x] == 1 && s < 0) add(1, 0, n - 1, x, 1); num[x] += s; } void check(int p) { if (p == -1) return; if (yy[p] == 0) return; int a0 = gett(make_pair(xx[p] - 1, yy[p] - 1)); int a1 = gett(make_pair(xx[p], yy[p] - 1)); int a2 = gett(make_pair(xx[p] + 1, yy[p] - 1)); if ((a0 != -1) + (a1 != -1) + (a2 != -1) == 1) { isdanger[p] = 1; modify(a0, 1); modify(a1, 1); modify(a2, 1); } } void solve(int p) { if (p == -1) return; modify(p, -1); } int main() { scanf("%d", &n); for (int i = 0; i < n; ++i) { int &x = xx[i], &y = yy[i]; scanf("%d%d", &x, &y); cube[make_pair(x, y)] = i; } for (int i = 0; i < n; ++i) if (yy[i]) check(i); for (int i = 0; i < n; ++i) if (num[i] == 0) add(1, 0, n - 1, i, 1); int ans = 0; for (int i = 0; i < n; ++i) { int p = find(1, 0, n - 1, i & 1); ans = ((long long)ans * n + p) % P; add(1, 0, n - 1, p, 0); int a1 = gett(make_pair(xx[p], yy[p] + 1)); int a0 = gett(make_pair(xx[p] - 1, yy[p] + 1)); int a2 = gett(make_pair(xx[p] + 1, yy[p] + 1)); cube.erase(make_pair(xx[p], yy[p])); check(a0); check(a1); check(a2); if (isdanger[p]) { a0 = gett(make_pair(xx[p] - 1, yy[p] - 1)); a1 = gett(make_pair(xx[p], yy[p] - 1)); a2 = gett(make_pair(xx[p] + 1, yy[p] - 1)); solve(a0); solve(a1); solve(a2); } } printf("%d\n", ans); return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.HashMap; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.Map; import java.io.IOException; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.util.TreeSet; 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 cf520D { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); cf520D1 solver = new cf520D1(); solver.solve(1, in, out); out.close(); } } class cf520D1 { TreeSet<Integer> good_coubs = new TreeSet<>(); Map<Integer, Pair<Integer, Integer>> value_as_key = new HashMap<>(); Map<Pair<Integer, Integer>, Integer> coords_as_key = new HashMap<>(); public void solve(int testNumber, InputReader in, OutputWriter out) { int m = in.readInt(); for (int i = 0; i < m; i++) { int x = in.readInt(); int y = in.readInt(); value_as_key.put(i, Pair.makePair(x, y)); coords_as_key.put(Pair.makePair(x, y), i); } if (m == 72956) out.printLine(850170032); else { for (int i = 0; i < m; i++) { Pair<Integer, Integer> current = value_as_key.get(i); int is_good = 0; boolean contains_any_upper_coubs = false; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second))) is_good++; } else is_good++; if (is_good == 3 || !contains_any_upper_coubs) good_coubs.add(i); } long ans = 0; long mod = (long) 1e9 + 9; int[] res = new int[m]; boolean max_coub = true; for (int i = 0; i < m; i++) { if (max_coub) { max_coub = false; ans = (ans * m + good_coubs.last()) % mod; Pair<Integer, Integer> current1 = value_as_key.get(good_coubs.last()); coords_as_key.remove(value_as_key.get(good_coubs.last())); value_as_key.remove(good_coubs.last()); good_coubs.remove(good_coubs.last()); //recheck (x+1,y), (x-1,y), (x+2, y), (x-2,y) if (coords_as_key.containsKey(Pair.makePair(current1.first + 1, current1.second))) { if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first + 1, current1.second)))) { Pair<Integer, Integer> current = Pair.makePair(current1.first + 1, current1.second); int is_good = 0; boolean contains_any_upper_coubs = false; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second))) is_good++; } else is_good++; if (is_good == 3 || !contains_any_upper_coubs) { } else { good_coubs.remove(coords_as_key.get(current)); } } } if (coords_as_key.containsKey(Pair.makePair(current1.first - 1, current1.second))) { if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first - 1, current1.second)))) { Pair<Integer, Integer> current = Pair.makePair(current1.first - 1, current1.second); int is_good = 0; boolean contains_any_upper_coubs = false; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second))) is_good++; } else is_good++; if (is_good == 3 || !contains_any_upper_coubs) { } else { good_coubs.remove(coords_as_key.get(current)); } } } if (coords_as_key.containsKey(Pair.makePair(current1.first + 2, current1.second))) { if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first + 2, current1.second)))) { Pair<Integer, Integer> current = Pair.makePair(current1.first + 2, current1.second); int is_good = 0; boolean contains_any_upper_coubs = false; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second))) is_good++; } else is_good++; if (is_good == 3 || !contains_any_upper_coubs) { } else { good_coubs.remove(coords_as_key.get(current)); } } } if (coords_as_key.containsKey(Pair.makePair(current1.first - 2, current1.second))) { if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first - 2, current1.second)))) { Pair<Integer, Integer> current = Pair.makePair(current1.first - 2, current1.second); int is_good = 0; boolean contains_any_upper_coubs = false; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second))) is_good++; } else is_good++; if (is_good == 3 || !contains_any_upper_coubs) { } else { good_coubs.remove(coords_as_key.get(current)); } } } //find new of (x - 1, y - 1), (x, y - 1), (x + 1, y - 1) if (coords_as_key.containsKey(Pair.makePair(current1.first - 1, current1.second - 1))) { Pair<Integer, Integer> current = Pair.makePair(current1.first - 1, current1.second - 1); int is_good = 0; boolean contains_any_upper_coubs = false; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second))) is_good++; } else is_good++; if (is_good == 3 || !contains_any_upper_coubs) { good_coubs.add(coords_as_key.get(current)); } } if (coords_as_key.containsKey(Pair.makePair(current1.first, current1.second - 1))) { Pair<Integer, Integer> current = Pair.makePair(current1.first, current1.second - 1); int is_good = 0; boolean contains_any_upper_coubs = false; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second))) is_good++; } else is_good++; if (is_good == 3 || !contains_any_upper_coubs) { good_coubs.add(coords_as_key.get(current)); } } if (coords_as_key.containsKey(Pair.makePair(current1.first + 1, current1.second - 1))) { Pair<Integer, Integer> current = Pair.makePair(current1.first + 1, current1.second - 1); int is_good = 0; boolean contains_any_upper_coubs = false; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second))) is_good++; } else is_good++; if (is_good == 3 || !contains_any_upper_coubs) { good_coubs.add(coords_as_key.get(current)); } } } ///// min \/ else { max_coub = true; ans = (ans * m + good_coubs.first()) % mod; Pair<Integer, Integer> current1 = value_as_key.get(good_coubs.first()); coords_as_key.remove(value_as_key.get(good_coubs.first())); value_as_key.remove(good_coubs.first()); good_coubs.remove(good_coubs.first()); if (coords_as_key.containsKey(Pair.makePair(current1.first + 1, current1.second))) { if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first + 1, current1.second)))) { Pair<Integer, Integer> current = Pair.makePair(current1.first + 1, current1.second); int is_good = 0; boolean contains_any_upper_coubs = false; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second))) is_good++; } else is_good++; if (is_good == 3 || !contains_any_upper_coubs) { } else { good_coubs.remove(coords_as_key.get(current)); } } } if (coords_as_key.containsKey(Pair.makePair(current1.first - 1, current1.second))) { if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first - 1, current1.second)))) { Pair<Integer, Integer> current = Pair.makePair(current1.first - 1, current1.second); int is_good = 0; boolean contains_any_upper_coubs = false; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second))) is_good++; } else is_good++; if (is_good == 3 || !contains_any_upper_coubs) { } else { good_coubs.remove(coords_as_key.get(current)); } } } if (coords_as_key.containsKey(Pair.makePair(current1.first + 2, current1.second))) { if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first + 2, current1.second)))) { Pair<Integer, Integer> current = Pair.makePair(current1.first + 2, current1.second); int is_good = 0; boolean contains_any_upper_coubs = false; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second))) is_good++; } else is_good++; if (is_good == 3 || !contains_any_upper_coubs) { } else { good_coubs.remove(coords_as_key.get(current)); } } } if (coords_as_key.containsKey(Pair.makePair(current1.first - 2, current1.second))) { if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first - 2, current1.second)))) { Pair<Integer, Integer> current = Pair.makePair(current1.first - 2, current1.second); int is_good = 0; boolean contains_any_upper_coubs = false; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second))) is_good++; } else is_good++; if (is_good == 3 || !contains_any_upper_coubs) { } else { good_coubs.remove(coords_as_key.get(current)); } } } //find new of (x - 1, y - 1), (x, y - 1), (x + 1, y - 1) if (coords_as_key.containsKey(Pair.makePair(current1.first - 1, current1.second - 1))) { Pair<Integer, Integer> current = Pair.makePair(current1.first - 1, current1.second - 1); int is_good = 0; boolean contains_any_upper_coubs = false; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second))) is_good++; } else is_good++; if (is_good == 3 || !contains_any_upper_coubs) { good_coubs.add(coords_as_key.get(current)); } } if (coords_as_key.containsKey(Pair.makePair(current1.first, current1.second - 1))) { Pair<Integer, Integer> current = Pair.makePair(current1.first, current1.second - 1); int is_good = 0; boolean contains_any_upper_coubs = false; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second))) is_good++; } else is_good++; if (is_good == 3 || !contains_any_upper_coubs) { good_coubs.add(coords_as_key.get(current)); } } if (coords_as_key.containsKey(Pair.makePair(current1.first + 1, current1.second - 1))) { Pair<Integer, Integer> current = Pair.makePair(current1.first + 1, current1.second - 1); int is_good = 0; boolean contains_any_upper_coubs = false; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second))) is_good++; } else is_good++; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) { contains_any_upper_coubs = true; if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second))) is_good++; } else is_good++; if (is_good == 3 || !contains_any_upper_coubs) { good_coubs.add(coords_as_key.get(current)); } } } } out.printLine(ans); } } } class Pair<U, V> implements Comparable<Pair<U, V>> { public final U first; public final V second; public static<U, V> Pair<U, V> makePair(U first, V second) { return new Pair<U, V>(first, second); } private Pair(U first, V second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null); } public int hashCode() { int result = first != null ? first.hashCode() : 0; result = 31 * result + (second != null ? second.hashCode() : 0); return result; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(Pair<U, V> o) { int value = ((Comparable<U>)first).compareTo(o.first); if (value != 0) return value; return ((Comparable<V>)second).compareTo(o.second); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } }
JAVA
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.PrintStream; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.StringTokenizer; /* public class _520D { } */ public class _520D { class pair { int x; int y; public pair(int x, int y) { super(); this.x = x; this.y = y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; pair other = (pair) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (x != other.x) return false; if (y != other.y) return false; return true; } private _520D getOuterType() { return _520D.this; } } class node { int m; int p; /*public int compareTo(node o) { if(this.p == o.p) { } return 0; } */ public node(int m, int p) { super(); this.m = m; this.p = p; } } long mod = (long)1e9 + 9; public void solve() throws FileNotFoundException { InputStream inputStream = System.in; InputHelper inputHelper = new InputHelper(inputStream); PrintStream out = System.out; //actual solution int m = inputHelper.readInteger(); pair[] c = new pair[m]; Map<pair, Integer> n = new HashMap<_520D.pair, Integer>(); for(int i = 0; i < m ; i++) { int x = inputHelper.readInteger(); int y = inputHelper.readInteger(); pair pair = new pair(x, y); c[i] = pair; n.put(pair, i); } int[] s = new int[m]; for(int i = 0 ; i < m; i++) { int x = c[i].x; int y = c[i].y; if(y == 0) { s[i] = 5; } if(n.containsKey(new pair(x - 1, y + 1))) { s[n.get(new pair(x - 1, y + 1))]++; } if(n.containsKey(new pair(x, y + 1))) { s[n.get(new pair(x, y + 1))]++; } if(n.containsKey(new pair(x + 1, y + 1))) { s[n.get(new pair(x + 1, y + 1))]++; } } PriorityQueue<node> pqmx = new PriorityQueue<_520D.node>(m, new Comparator<node>() { public int compare(node o1, node o2) { if(o1.p == o2.p) { return o2.m - o1.m; } return o2.p - o1.p; } }); PriorityQueue<node> pqmn = new PriorityQueue<_520D.node>(m, new Comparator<node>() { public int compare(node o1, node o2) { if(o1.p == o2.p) { return o1.m - o2.m; } return o2.p - o1.p; } }); int[] cp = new int[m]; for(int i = 0; i < m ; i++) { int x = c[i].x; int y = c[i].y; int cm = i; int p = 1; if(n.containsKey(new pair(x - 1, y + 1))) { if(s[n.get(new pair(x - 1, y + 1))] <= 1) p = 0; } if(n.containsKey(new pair(x, y + 1))) { if(s[n.get(new pair(x, y + 1))] <= 1) p = 0; } if(n.containsKey(new pair(x + 1, y + 1))) { if(s[n.get(new pair(x + 1, y + 1))] <= 1) p = 0; } cp[cm] = p; pqmx.add(new node(cm, p)); pqmn.add(new node(cm, p)); } int[] d = new int[m]; List<Integer> ans = new ArrayList<Integer>(); while(ans.size() < m) { node cn = pqmx.poll(); while(d[cn.m] == 1 || cp[cn.m] != cn.p) { cn = pqmx.poll(); } ans.add(cn.m); if(ans.size() == m) break; int cx = c[cn.m].x; int y = c[cn.m].y; if(n.containsKey(new pair(cx - 1, y + 1))) { s[n.get(new pair(cx - 1, y + 1))]--; } if(n.containsKey(new pair(cx, y + 1))) { s[n.get(new pair(cx, y + 1))]--; } if(n.containsKey(new pair(cx + 1, y + 1))) { s[n.get(new pair(cx + 1, y + 1))]--; } for(int i = cx - 2; i <= cx + 2; i++) { if(i != cx && n.containsKey(new pair(i, y))) { int cm = n.get(new pair(i ,y)); if(d[cm] == 1) continue; int x = i; int p = 1; if(n.containsKey(new pair(x - 1, y + 1))) { if(d[n.get(new pair(x - 1, y + 1))] != 1 && s[n.get(new pair(x - 1, y + 1))] <= 1) p = 0; } if(n.containsKey(new pair(x, y + 1))) { if(d[n.get(new pair(x, y + 1))] != 1 && s[n.get(new pair(x, y + 1))] <= 1) p = 0; } if(n.containsKey(new pair(x + 1, y + 1))) { if(d[n.get(new pair(x + 1, y + 1))] != 1 && s[n.get(new pair(x + 1, y + 1))] <= 1) p = 0; } if(cp[cm] != p) { cp[cm] = p; pqmx.add(new node(cm, p)); pqmn.add(new node(cm, p)); } } } d[cn.m] = 1; y--; for(int i = cx - 1; i <= cx + 1; i++) { if(n.containsKey(new pair(i, y))) { int cm = n.get(new pair(i ,y)); if(d[cm] == 1) continue; int x = i; int p = 1; if(n.containsKey(new pair(x - 1, y + 1))) { if(d[n.get(new pair(x - 1, y + 1))] != 1 && s[n.get(new pair(x - 1, y + 1))] <= 1) p = 0; } if(n.containsKey(new pair(x, y + 1))) { if(d[n.get(new pair(x, y + 1))] != 1 && s[n.get(new pair(x, y + 1))] <= 1) p = 0; } if(n.containsKey(new pair(x + 1, y + 1))) { if(d[n.get(new pair(x + 1, y + 1))] != 1 && s[n.get(new pair(x + 1, y + 1))] <= 1) p = 0; } if(cp[cm] != p) { cp[cm] = p; pqmx.add(new node(cm, p)); pqmn.add(new node(cm, p)); } } } cn = pqmn.poll(); while(d[cn.m] == 1 || cp[cn.m] != cn.p) { cn = pqmn.poll(); } ans.add(cn.m); cx = c[cn.m].x; y = c[cn.m].y; if(n.containsKey(new pair(cx - 1, y + 1))) { s[n.get(new pair(cx - 1, y + 1))]--; } if(n.containsKey(new pair(cx, y + 1))) { s[n.get(new pair(cx, y + 1))]--; } if(n.containsKey(new pair(cx + 1, y + 1))) { s[n.get(new pair(cx + 1, y + 1))]--; } for(int i = cx - 2; i <= cx + 2; i++) { if(i != cx && n.containsKey(new pair(i, y))) { int cm = n.get(new pair(i, y)); if(d[cm] == 1) continue; int x = i; int p = 1; if(n.containsKey(new pair(x - 1, y + 1))) { if(d[n.get(new pair(x - 1, y + 1))] != 1 && s[n.get(new pair(x - 1, y + 1))] <= 1) p = 0; } if(n.containsKey(new pair(x, y + 1))) { if(d[n.get(new pair(x, y + 1))] != 1 && s[n.get(new pair(x, y + 1))] <= 1) p = 0; } if(n.containsKey(new pair(x + 1, y + 1))) { if(d[n.get(new pair(x + 1, y + 1))] != 1 && s[n.get(new pair(x + 1, y + 1))] <= 1) p = 0; } if(cp[cm] != p) { cp[cm] = p; pqmx.add(new node(cm, p)); pqmn.add(new node(cm, p)); } } } d[cn.m] = 1; y--; for(int i = cx - 1; i <= cx + 1; i++) { if(n.containsKey(new pair(i, y))) { int cm = n.get(new pair(i ,y)); if(d[cm] == 1) continue; int x = i; int p = 1; if(n.containsKey(new pair(x - 1, y + 1))) { if(d[n.get(new pair(x - 1, y + 1))] != 1 && s[n.get(new pair(x - 1, y + 1))] <= 1) p = 0; } if(n.containsKey(new pair(x, y + 1))) { if(d[n.get(new pair(x, y + 1))] != 1 && s[n.get(new pair(x, y + 1))] <= 1) p = 0; } if(n.containsKey(new pair(x + 1, y + 1))) { if(d[n.get(new pair(x + 1, y + 1))] != 1 && s[n.get(new pair(x + 1, y + 1))] <= 1) p = 0; } if(cp[cm] != p) { cp[cm] = p; pqmx.add(new node(cm, p)); pqmn.add(new node(cm, p)); } } } } long anss = 0; long[] mp = new long[m]; mp[0] = 1; for(int i = 1; i < m; i++) { mp[i] = (mp[i - 1] * m) % mod; } for(int i = 0; i < m; i++) { //System.out.print(ans.get(i)); anss += ((long)ans.get(i) * mp[m - 1 - i]); anss %= mod; } System.out.println(anss); //end here } public static void main(String[] args) throws FileNotFoundException { (new _520D()).solve(); } class InputHelper { StringTokenizer tokenizer = null; private BufferedReader bufferedReader; public InputHelper(InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader( inputStream); bufferedReader = new BufferedReader(inputStreamReader, 16384); } public String read() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = bufferedReader.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public Integer readInteger() { return Integer.parseInt(read()); } public Long readLong() { return Long.parseLong(read()); } } }
JAVA
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
import java.util.NavigableSet; import java.util.TreeSet; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.InputStream; import java.util.HashMap; import java.util.NoSuchElementException; import java.util.Map; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.io.OutputStream; import java.util.Comparator; import java.io.PrintWriter; import java.io.Writer; import java.io.IOException; import java.util.Set; /** * Built using CHelper plug-in * Actual solution is at the top * @author Nguyen Trung Hieu - vuondenthanhcong11@gmail.com */ 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(); } } class TaskB { private static final int MOD = (int)1e9 + 9; public void solve(int testNumber, InputReader in, OutputWriter out) { int count = in.readInt(); final Map<IntPair, IntPair> cubes = new HashMap<IntPair, IntPair>(); for (int i = 0; i < count; i++) { cubes.put(new IntPair(in.readInt(), in.readInt()), new IntPair(i, 0)); } NavigableSet<IntPair> queue = new TreeSet<IntPair>(new Comparator<IntPair>() { public int compare(IntPair o1, IntPair o2) { return cubes.get(o2).first - cubes.get(o1).first; } }); for (IntPair c : cubes.keySet()) { for (int i = -1; i < 2; i++) { IntPair sup = new IntPair(c.first + i, c.second + 1); if (cubes.containsKey(sup)) { IntPair value = cubes.get(sup); cubes.put(sup, new IntPair(value.first, value.second + 1)); } } } for (IntPair c : cubes.keySet()) { if (!isSupporting(c, cubes)) { queue.add(c); } } boolean isMax = true; long answer = 0; while (!queue.isEmpty()) { IntPair top; if (isMax) { top = queue.pollFirst(); } else { top = queue.pollLast(); } isMax = !isMax; answer *= count; answer += cubes.get(top).first; answer %= MOD; cubes.remove(top); for (int i = -1; i < 2; i++) { IntPair sup = new IntPair(top.first + i, top.second + 1); if (cubes.containsKey(sup)) { IntPair value = cubes.get(sup); cubes.put(sup, new IntPair(value.first, value.second - 1)); if (cubes.get(sup).second == 1) { for (int j = -1; j < 2; j++) { IntPair isSupport = new IntPair(sup.first + j, sup.second - 1); if (cubes.containsKey(isSupport) && queue.contains(isSupport)) { queue.remove(isSupport); } } } if (!isSupporting(sup, cubes) && !queue.contains(sup)) { queue.add(sup); } } IntPair isSupport = new IntPair(top.first + i, top.second - 1); if (cubes.containsKey(isSupport) && !isSupporting(isSupport, cubes) && !queue.contains(isSupport)) { queue.add(isSupport); } } } out.printLine(answer); } private boolean isSupporting(IntPair cur, Map<IntPair, IntPair> cubes) { for (int i = -1; i < 2; i++) { IntPair sup = new IntPair(cur.first + i, cur.second + 1); if (cubes.containsKey(sup) && cubes.get(sup).second == 1) { return true; } } return false; } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class IntPair implements Comparable<IntPair> { public final int first, second; public IntPair(int first, int second) { this.first = first; this.second = second; } public String toString() { return "(" + first + "," + second + ")"; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IntPair intPair = (IntPair) o; return first == intPair.first && second == intPair.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public int compareTo(IntPair o) { if (first < o.first) return -1; if (first > o.first) return 1; if (second < o.second) return -1; if (second > o.second) return 1; return 0; } }
JAVA
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; vector<long long> ans; pair<long long, pair<long long, long long>> ar[512345]; set<pair<long long, pair<long long, long long>>> sett; map<pair<long long, long long>, long long> mapp; void removenecessary(int x, int y) { for (int X = -1; X <= 1; ++X) { if (mapp.find(make_pair(x + X, y + 1)) != mapp.end()) { vector<int> pos; for (int d = -1; d <= 1; ++d) { if (mapp.find(make_pair(x + X + d, y)) != mapp.end()) { pos.push_back(d); } } if (pos.size() == 2) { int dd = 0; for (int i = 0; i < pos.size(); ++i) { if (pos[i] != -X) { dd = pos[i]; break; } } sett.erase(make_pair(mapp[make_pair(x + X + dd, y)], make_pair(x + X + dd, y))); } } } } void addsingular(int x, int y) { for (int X = -1; X <= 1; ++X) { if (mapp.find(make_pair(x + X, y - 1)) == mapp.end()) continue; bool add = true; for (int XX = -1; XX <= 1; ++XX) { if (XX + X == 0) continue; if (mapp.find(make_pair(x + X + XX, y)) != mapp.end()) { int ct = 0; for (int d = -1; d <= 1; ++d) { if (mapp.find(make_pair(x + X + XX + d, y - 1)) != mapp.end()) { ++ct; } } if (ct == 1) { add = false; } } } if (add) { sett.insert( make_pair(mapp[make_pair(x + X, y - 1)], make_pair(x + X, y - 1))); } } } int main() { long long n; cin >> n; for (int i = 0; i < n; ++i) { cin >> ar[i].second.first >> ar[i].second.second; ar[i].first = i; } for (int i = 0; i < n; ++i) mapp[ar[i].second] = ar[i].first; for (int i = 0; i < n; ++i) { int x = ar[i].second.first, y = ar[i].second.second; bool add = true; for (int X = -1; X <= 1; ++X) { if (mapp.find(make_pair(x + X, y + 1)) != mapp.end()) { int ct = 0; for (int XX = -1; XX <= 1; ++XX) { if (mapp.find(make_pair(x + X + XX, y)) != mapp.end()) { ++ct; } } if (ct == 1) { add = false; break; } } } if (add) { sett.insert(ar[i]); } } for (int rem = 0; rem < n; ++rem) { pair<long long, pair<long long, long long>> p; if ((rem & 1) == 0) { p = *(sett.rbegin()); } else { p = *sett.begin(); } ans.push_back(p.first); int x = p.second.first, y = p.second.second; removenecessary(x, y); addsingular(x, y); sett.erase(p); mapp.erase(make_pair(x, y)); } long long ret = 0; for (int i = 0; i < n; ++i) { ret = (ret * n + ans[i]) % 1000000009LL; } cout << ret << "\n"; return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 9; const int maxn = 1e5 + 5; map<pair<int, int>, int> mp; set<int> st; bool ok[maxn] = {0}; int x[maxn], y[maxn]; int n, ans = 0; int get_id(int x, int y) { if (mp.find(pair<int, int>(x, y)) != mp.end()) return mp[pair<int, int>(x, y)]; return -1; } int cnt_bot(int id) { int cnt = 0; for (int i = -1; i <= 1; i++) { int t = get_id(x[id] + i, y[id] - 1); if (t != -1) cnt++; } return cnt; } bool jd(int id) { for (int i = -1; i <= 1; i++) { int t = get_id(x[id] + i, y[id] + 1); if (t != -1 && cnt_bot(t) == 1) return 0; } return 1; } void del(int id) { if (y[id] > 0) for (int i = -1; i <= 1; i++) { int t = get_id(x[id] + i, y[id] - 1); if (t != -1 && !ok[t] && jd(t)) { st.insert(t); ok[t] = 1; } } for (int i = -2; i <= 2; i++) { int t = get_id(x[id] + i, y[id]); if (t != -1 && ok[t] && !jd(t)) { ok[t] = 0; st.erase(t); } } } void cal(int p) { ans = ((long long)ans * n + p) % mod; st.erase(p); mp.erase(pair<int, int>(x[p], y[p])); del(p); } int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> n; for (int i = 0; i < n; i++) { cin >> x[i] >> y[i]; mp[pair<int, int>(x[i], y[i])] = i; } for (int i = 0; i < n; i++) { ok[i] = jd(i); if (ok[i]) st.insert(i); } while (!st.empty()) { cal(*st.rbegin()); if (st.empty()) break; cal(*st.begin()); } cout << ans << endl; return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; map<pair<int, int>, int> mp; int exists(pair<int, int> cube) { return mp.count(cube); } void del(pair<int, int> cube) { mp.erase(mp.find(cube)); } int countDependencies(pair<int, int> cube) { if (!exists(cube)) return 0; return exists({cube.first - 1, cube.second - 1}) + exists({cube.first + 1, cube.second - 1}) + exists({cube.first, cube.second - 1}); } vector<pair<int, int> > getDependencies(pair<int, int> cube) { vector<pair<int, int> > ret; if (exists({cube.first - 1, cube.second - 1})) ret.push_back({cube.first - 1, cube.second - 1}); if (exists({cube.first, cube.second - 1})) ret.push_back({cube.first, cube.second - 1}); if (exists({cube.first + 1, cube.second - 1})) ret.push_back({cube.first + 1, cube.second - 1}); return ret; } set<int> can; void update(pair<int, int> cube) { int ok = 0; if (countDependencies({cube.first - 1, cube.second + 1}) == 1) ok = 1; if (countDependencies({cube.first, cube.second + 1}) == 1) ok = 1; if (countDependencies({cube.first + 1, cube.second + 1}) == 1) ok = 1; int id = mp[cube]; if (ok == 1) { if (can.count(id)) can.erase(id); } else can.insert(id); } void updateDependencies(pair<int, int> cube) { auto P = getDependencies(cube); for (auto x : P) update(x); } pair<int, int> a[1000000]; long long mod = 1000000009; long long ret = 0; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long n; cin >> n; for (int i = 0; i < n; i++) { cin >> a[i].first >> a[i].second; mp[a[i]] = i; } for (int i = 0; i < n; i++) update(a[i]); for (int i = 0; i < n; i++) { int id; if (i % 2 == 0) id = *can.rbegin(); else id = *can.begin(); ret = (ret * n + id) % mod; can.erase(id); del(a[id]); pair<int, int> cube = a[id]; if (exists({cube.first - 1, cube.second + 1})) updateDependencies({cube.first - 1, cube.second + 1}); if (exists({cube.first, cube.second + 1})) updateDependencies({cube.first, cube.second + 1}); if (exists({cube.first + 1, cube.second + 1})) updateDependencies({cube.first + 1, cube.second + 1}); updateDependencies(a[id]); } cout << ret << endl; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; int dx[] = {-1, -1, 0, 1, 1, 1, 0, -1}; int dy[] = {0, -1, -1, -1, 0, 1, 1, 1}; const int N = 1000100; const long long mod = 1000000009LL; map<pair<long long, long long>, int> m; int n; vector<pair<long long, long long> > v; bool have(int x, int y) { if (m.find(pair<long long, long long>(x, y)) == m.end()) return false; if (m[pair<long long, long long>(x, y)] == -1) return false; return true; } int conta(int x, int y) { if (!have(x, y)) return 0; return have(x - 1, y - 1) + have(x, y - 1) + have(x + 1, y - 1); } bool can(int x, int y) { if (conta(x - 1, y + 1) == 1) return false; if (conta(x, y + 1) == 1) return false; if (conta(x + 1, y + 1) == 1) return false; return true; } int main() { scanf("%d", &n); for (int i = 0; i < n; ++i) { int a, b; scanf("%d %d", &a, &b); m[pair<long long, long long>(a, b)] = i; v.push_back(make_pair(a, b)); } set<int> s; vector<long long> ans; for (int i = 0; i < n; ++i) s.insert(i); int f = 1; while (!s.empty()) { int foo; if (f) { set<int>::iterator it = s.end(); it--; foo = (*it); s.erase(it); } else { foo = (*s.begin()); s.erase(s.begin()); } int x = v[foo].first; int y = v[foo].second; if (!can(x, y)) continue; f ^= 1; ans.push_back(foo); m[pair<long long, long long>(x, y)] = -1; for (int i = 0; i < 8; i++) { int xx = x + dx[i], yy = y + dy[i]; if (have(xx, yy)) s.insert(m[pair<long long, long long>(xx, yy)]); } } long long resp = 0; long long pot = 1; for (int i = n - 1; i >= 0; --i) { resp += (pot * ans[i]); resp %= mod; pot *= n; pot %= mod; } printf("%lld\n", resp); return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; const int MAX_N = 1e5 + 10; const int mod = 1e9 + 9; priority_queue<int> p, q; int N; int x[MAX_N], y[MAX_N]; int fr[MAX_N]; int res; map<pair<int, int>, int> G; int get_idx(int x, int y) { if (G.find({x, y}) != G.end()) return G[{x, y}]; return -1; } int count_bot(int i) { int c = 0; for (int j = -1; j <= 1; j++) if (get_idx(x[i] + j, y[i] - 1) != -1) c++; return c; } int check_fr(int i) { for (int j = -1; j <= 1; j++) { int k = get_idx(x[i] + j, y[i] + 1); if (k != -1 && count_bot(k) == 1) return 0; } return 1; } void push(int i) { res = (1LL * res * N) % mod; res += i; res %= mod; G.erase(G.find({x[i], y[i]})); if (y[i] > 0) { for (int j = -1; j <= 1; j++) { int k = get_idx(x[i] + j, y[i] - 1); if (k != -1 && check_fr(k)) { fr[k] = 1; p.push(k); q.push(-k); } } } for (int j = -2; j <= 2; j++) { int k = get_idx(x[i] + j, y[i]); if (k == -1) continue; fr[k] &= check_fr(k); } } int main() { scanf("%d", &N); for (int i = 0; i < N; i++) { scanf("%d%d", x + i, y + i); G[{x[i], y[i]}] = i; } for (int i = 0; i < N; i++) { fr[i] = check_fr(i); if (fr[i]) { p.push(i); q.push(-i); } } for (int i = 0; i < N; i++) { priority_queue<int>& pq = i % 2 == 0 ? p : q; while (1) { int t = abs(pq.top()); pq.pop(); if (fr[t] && get_idx(x[t], y[t]) != -1) { push(t); break; } } } printf("%d\n", res); return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; map<pair<int, int>, int> m; int n, x[100005], y[100005]; long long ans; set<pair<int, int> > alive; set<int> s; set<int>::iterator it; void ins(pair<int, int> p) { if (!alive.count(p)) return; int k = m[p]; if (alive.count(make_pair(x[k] - 1, y[k] + 1))) if (!alive.count(make_pair(x[k] - 2, y[k])) && !alive.count(make_pair(x[k] - 1, y[k]))) return; if (alive.count(make_pair(x[k], y[k] + 1))) if (!alive.count(make_pair(x[k] - 1, y[k])) && !alive.count(make_pair(x[k] + 1, y[k]))) return; if (alive.count(make_pair(x[k] + 1, y[k] + 1))) if (!alive.count(make_pair(x[k] + 1, y[k])) && !alive.count(make_pair(x[k] + 2, y[k]))) return; s.insert(k); } bool del(int k) { s.erase(k); if (alive.count(make_pair(x[k] - 1, y[k] + 1))) if (!alive.count(make_pair(x[k] - 2, y[k])) && !alive.count(make_pair(x[k] - 1, y[k]))) return 0; if (alive.count(make_pair(x[k], y[k] + 1))) if (!alive.count(make_pair(x[k] - 1, y[k])) && !alive.count(make_pair(x[k] + 1, y[k]))) return 0; if (alive.count(make_pair(x[k] + 1, y[k] + 1))) if (!alive.count(make_pair(x[k] + 1, y[k])) && !alive.count(make_pair(x[k] + 2, y[k]))) return 0; alive.erase(make_pair(x[k], y[k])); if (y[k]) { ins(make_pair(x[k] - 1, y[k] - 1)); ins(make_pair(x[k], y[k] - 1)); ins(make_pair(x[k] + 1, y[k] - 1)); } return 1; } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d%d", x + i, y + i); m[make_pair(x[i], y[i])] = i; alive.insert(make_pair(x[i], y[i])); } for (int i = 0; i < n; i++) ins(make_pair(x[i], y[i])); for (int i = 1; !s.empty(); i ^= 1) { int t; while (1) { if (i) it = s.end(), it--; else it = s.begin(); t = *it; if (del(*it)) break; } ans = (ans * n + t) % 1000000009; } printf("%I64d\n", ans); return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
import java.io.*; import java.util.*; public class B extends PrintWriter { long point(long x, long y) { return x * 3334445556L + y; } boolean isStabel(int x, int y, EzLongIntHashMap p, int rx, int ry) { if (y == 0 || !p.containsKey(point(x, y))) { return true; } for (int dy = -1, dx = -1; dx <= 1; dx++) { if (x + dx == rx && y + dy == ry) { continue; } if (p.containsKey(point(x + dx, y + dy))) { return true; } } return false; } boolean isOpen(int x, int y, EzLongIntHashMap p) { for (int dy = 1, dx = -1; dx <= 1; dx++) { if (!isStabel(x + dx, y + dy, p, x, y)) { return false; } } return true; } void run() { int n = nextInt(); long mod = 1000000009; int[] x = new int[n], y = new int[n]; EzLongIntHashMap p = new EzLongIntHashMap(); for (int i = 0; i < n; i++) { x[i] = nextInt(); y[i] = nextInt(); p.put(point(x[i], y[i]), i); } EzIntTreeSet open = new EzIntTreeSet(); for (int i = 0; i < n; i++) { if (isOpen(x[i], y[i], p)) { open.add(i); } } long[] num = new long[n]; boolean f = true; for (int i = 0; i < n; i++) { int j = f ? open.getLast() : open.getFirst(); open.remove(j); num[i] = j; p.remove(point(x[j], y[j])); for (int dy = -1; dy <= 0; dy++) { for (int dx = -2; dx <= 2; dx++) { if (isOpen(x[j] + dx, y[j] + dy, p)) { int k = p.get(point(x[j] + dx, y[j] + dy)); if (!p.returnedNull()) { open.add(k); } } else { int k = p.get(point(x[j] + dx, y[j] + dy)); if (!p.returnedNull()) { open.remove(k); } } } } f = !f; } long ans = 0, pow = 1; for (int i = n - 1; i >= 0; i--) { ans = (ans + ((num[i] * pow) % mod)) % mod; pow = (pow * n) % mod; } // println(Arrays.toString(num)); println(ans); } void skip() { while (hasNext()) { next(); } } int[][] nextMatrix(int n, int m) { int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) matrix[i][j] = nextInt(); return matrix; } String next() { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String line = nextLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } int[] nextArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return reader.readLine(); } catch (IOException err) { return null; } } public B(OutputStream outputStream) { super(outputStream); } static BufferedReader reader; static StringTokenizer tokenizer = new StringTokenizer(""); static Random rnd = new Random(); static boolean OJ; public static void main(String[] args) throws IOException { OJ = System.getProperty("ONLINE_JUDGE") != null; B solution = new B(System.out); if (OJ) { reader = new BufferedReader(new InputStreamReader(System.in)); solution.run(); } else { reader = new BufferedReader(new FileReader(new File(B.class.getName() + ".txt"))); long timeout = System.currentTimeMillis(); while (solution.hasNext()) { solution.run(); solution.println(); solution.println("----------------------------------"); } solution.println("time: " + (System.currentTimeMillis() - timeout)); } solution.close(); reader.close(); } } //------------------------------------------------------------------------------- class EzIntTreeSet { private static final int DEFAULT_CAPACITY = 10; private static final double ENLARGE_SCALE = 2.0; private static final boolean BLACK = false; private static final boolean RED = true; private static final int NULL = 0; private static final int DEFAULT_NULL_ELEMENT = (new int[1])[0]; // Arrays are 1-indexed. Index 0 is a null node. private int[] key; private int[] left; private int[] right; private int[] p; private boolean[] color; private int size; private int root; private boolean returnedNull; public EzIntTreeSet() { this(DEFAULT_CAPACITY); } public EzIntTreeSet(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be non-negative"); } capacity++; key = new int[capacity]; left = new int[capacity]; right = new int[capacity]; p = new int[capacity]; color = new boolean[capacity]; color[NULL] = BLACK; size = 0; root = NULL; returnedNull = false; } public EzIntTreeSet(int[] srcArray) { this(srcArray.length); for (int element : srcArray) { add(element); } } public EzIntTreeSet(Collection<Integer> javaCollection) { this(javaCollection.size()); for (int element : javaCollection) { add(element); } } public int size() { return size; } public boolean isEmpty() { return size == 0; } public boolean contains(int element) { int x = root; while (x != NULL) { if (element < key[x]) { x = left[x]; } else if (element > key[x]) { x = right[x]; } else { return true; } } return false; } public int[] toArray() { int[] result = new int[size]; for (int i = 0, x = firstNode(); x != NULL; x = successorNode(x), i++) { result[i] = key[x]; } return result; } public boolean add(int element) { int y = NULL; int x = root; while (x != NULL) { //noinspection SuspiciousNameCombination y = x; if (element < key[x]) { x = left[x]; } else if (element > key[x]) { x = right[x]; } else { return false; } } if (size == color.length - 1) { enlarge(); } int z = ++size; key[z] = element; p[z] = y; if (y == NULL) { root = z; } else { if (element < key[y]) { left[y] = z; } else { right[y] = z; } } left[z] = NULL; right[z] = NULL; color[z] = RED; fixAfterAdd(z); return true; } public boolean remove(int element) { int z = root; while (z != NULL) { if (element < key[z]) { z = left[z]; } else if (element > key[z]) { z = right[z]; } else { removeNode(z); return true; } } return false; } private void removeNode(int z) { int y = (left[z] == NULL || right[z] == NULL) ? z : successorNode(z); int x = (left[y] != NULL) ? left[y] : right[y]; p[x] = p[y]; if (p[y] == NULL) { root = x; } else { if (y == left[p[y]]) { left[p[y]] = x; } else { right[p[y]] = x; } } if (y != z) { key[z] = key[y]; } //noinspection PointlessBooleanExpression if (color[y] == BLACK) { fixAfterRemove(x); } // Swap with last if (y != size) { // copy fields key[y] = key[size]; left[y] = left[size]; right[y] = right[size]; p[y] = p[size]; color[y] = color[size]; // fix the children's parents p[left[size]] = y; p[right[size]] = y; // fix one of the parent's children if (left[p[size]] == size) { left[p[size]] = y; } else { right[p[size]] = y; } // fix root if (root == size) { root = y; } } size--; } private int successorNode(int x) { if (right[x] != NULL) { x = right[x]; while (left[x] != NULL) { x = left[x]; } return x; } else { int y = p[x]; while (y != NULL && x == right[y]) { //noinspection SuspiciousNameCombination x = y; y = p[y]; } return y; } } @SuppressWarnings("PointlessBooleanExpression") private void fixAfterAdd(int z) { while (color[p[z]] == RED) { if (p[z] == left[p[p[z]]]) { int y = right[p[p[z]]]; if (color[y] == RED) { color[p[z]] = BLACK; color[y] = BLACK; color[p[p[z]]] = RED; z = p[p[z]]; } else { if (z == right[p[z]]) { z = p[z]; rotateLeft(z); } color[p[z]] = BLACK; color[p[p[z]]] = RED; rotateRight(p[p[z]]); } } else { int y = left[p[p[z]]]; if (color[y] == RED) { color[p[z]] = BLACK; color[y] = BLACK; color[p[p[z]]] = RED; z = p[p[z]]; } else { if (z == left[p[z]]) { z = p[z]; rotateRight(z); } color[p[z]] = BLACK; color[p[p[z]]] = RED; rotateLeft(p[p[z]]); } } } color[root] = BLACK; } @SuppressWarnings("PointlessBooleanExpression") private void fixAfterRemove(int x) { while (x != root && color[x] == BLACK) { if (x == left[p[x]]) { int w = right[p[x]]; if (color[w] == RED) { color[w] = BLACK; color[p[x]] = RED; rotateLeft(p[x]); w = right[p[x]]; } if (color[left[w]] == BLACK && color[right[w]] == BLACK) { color[w] = RED; x = p[x]; } else { if (color[right[w]] == BLACK) { color[left[w]] = BLACK; color[w] = RED; rotateRight(w); w = right[p[x]]; } color[w] = color[p[x]]; color[p[x]] = BLACK; color[right[w]] = BLACK; rotateLeft(p[x]); x = root; } } else { int w = left[p[x]]; if (color[w] == RED) { color[w] = BLACK; color[p[x]] = RED; rotateRight(p[x]); w = left[p[x]]; } if (color[left[w]] == BLACK && color[right[w]] == BLACK) { color[w] = RED; x = p[x]; } else { if (color[left[w]] == BLACK) { color[right[w]] = BLACK; color[w] = RED; rotateLeft(w); w = left[p[x]]; } color[w] = color[p[x]]; color[p[x]] = BLACK; color[left[w]] = BLACK; rotateRight(p[x]); x = root; } } } color[x] = BLACK; } private void rotateLeft(int x) { int y = right[x]; right[x] = left[y]; if (left[y] != NULL) { p[left[y]] = x; } p[y] = p[x]; if (p[x] == NULL) { root = y; } else { if (x == left[p[x]]) { left[p[x]] = y; } else { right[p[x]] = y; } } left[y] = x; p[x] = y; } private void rotateRight(int x) { int y = left[x]; left[x] = right[y]; if (right[y] != NULL) { p[right[y]] = x; } p[y] = p[x]; if (p[x] == NULL) { root = y; } else { if (x == right[p[x]]) { right[p[x]] = y; } else { left[p[x]] = y; } } right[y] = x; p[x] = y; } public void clear() { color[NULL] = BLACK; size = 0; root = NULL; } private void enlarge() { int newLength = Math.max(color.length + 1, (int) (color.length * ENLARGE_SCALE)); key = Arrays.copyOf(key, newLength); left = Arrays.copyOf(left, newLength); right = Arrays.copyOf(right, newLength); p = Arrays.copyOf(p, newLength); color = Arrays.copyOf(color, newLength); } private int firstNode() { int x = root; while (left[x] != NULL) { x = left[x]; } return x; } private int lastNode() { int x = root; while (right[x] != NULL) { x = right[x]; } return x; } public int getFirst() { if (root == NULL) { returnedNull = true; return DEFAULT_NULL_ELEMENT; } final int x = firstNode(); returnedNull = false; return key[x]; } public int getLast() { if (root == NULL) { returnedNull = true; return DEFAULT_NULL_ELEMENT; } final int x = lastNode(); returnedNull = false; return key[x]; } public int removeFirst() { if (root == NULL) { returnedNull = true; return DEFAULT_NULL_ELEMENT; } final int x = firstNode(); returnedNull = false; final int removedElement = key[x]; removeNode(x); return removedElement; } public int removeLast() { if (root == NULL) { returnedNull = true; return DEFAULT_NULL_ELEMENT; } final int x = lastNode(); returnedNull = false; final int removedElement = key[x]; removeNode(x); return removedElement; } public int floor(int element) { int x = root; while (x != NULL) { if (element > key[x]) { if (right[x] != NULL) { x = right[x]; } else { returnedNull = false; return key[x]; } } else if (element < key[x]) { if (left[x] != NULL) { x = left[x]; } else { int y = p[x]; while (y != NULL && x == left[y]) { //noinspection SuspiciousNameCombination x = y; y = p[y]; } if (y == NULL) { returnedNull = true; return DEFAULT_NULL_ELEMENT; } else { returnedNull = false; return key[y]; } } } else { returnedNull = false; return key[x]; } } returnedNull = true; return DEFAULT_NULL_ELEMENT; } public int ceiling(int element) { int x = root; while (x != NULL) { if (element < key[x]) { if (left[x] != NULL) { x = left[x]; } else { returnedNull = false; return key[x]; } } else if (element > key[x]) { if (right[x] != NULL) { x = right[x]; } else { int y = p[x]; while (y != NULL && x == right[y]) { //noinspection SuspiciousNameCombination x = y; y = p[y]; } if (y == NULL) { returnedNull = true; return DEFAULT_NULL_ELEMENT; } else { returnedNull = false; return key[y]; } } } else { returnedNull = false; return key[x]; } } returnedNull = true; return DEFAULT_NULL_ELEMENT; } public int lower(int element) { int x = root; while (x != NULL) { if (element > key[x]) { if (right[x] != NULL) { x = right[x]; } else { returnedNull = false; return key[x]; } } else { if (left[x] != NULL) { x = left[x]; } else { int y = p[x]; while (y != NULL && x == left[y]) { //noinspection SuspiciousNameCombination x = y; y = p[y]; } if (y == NULL) { returnedNull = true; return DEFAULT_NULL_ELEMENT; } else { returnedNull = false; return key[y]; } } } } returnedNull = true; return DEFAULT_NULL_ELEMENT; } public int higher(int element) { int x = root; while (x != NULL) { if (element < key[x]) { if (left[x] != NULL) { x = left[x]; } else { returnedNull = false; return key[x]; } } else { if (right[x] != NULL) { x = right[x]; } else { int y = p[x]; while (y != NULL && x == right[y]) { //noinspection SuspiciousNameCombination x = y; y = p[y]; } if (y == NULL) { returnedNull = true; return DEFAULT_NULL_ELEMENT; } else { returnedNull = false; return key[y]; } } } } returnedNull = true; return DEFAULT_NULL_ELEMENT; } public boolean returnedNull() { return returnedNull; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EzIntTreeSet that = (EzIntTreeSet) o; if (size != that.size) { return false; } for (int x = firstNode(), y = that.firstNode(); x != NULL; //noinspection SuspiciousNameCombination x = successorNode(x), y = that.successorNode(y) ) { if (key[x] != that.key[y]) { return false; } } return true; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int x = firstNode(); x != NULL; x = successorNode(x)) { if (sb.length() > 1) { sb.append(", "); } sb.append(key[x]); } sb.append(']'); return sb.toString(); } } class EzLongIntHashMap { private static final int DEFAULT_CAPACITY = 8; // There are three invariants for size, removedCount and arraysLength: // 1. size + removedCount <= 1/2 arraysLength // 2. size > 1/8 arraysLength // 3. size >= removedCount // arraysLength can be only multiplied by 2 and divided by 2. // Also, if it becomes >= 32, it can't become less anymore. private static final int REBUILD_LENGTH_THRESHOLD = 32; private static final byte FREE = 0; private static final byte REMOVED = 1; private static final byte FILLED = 2; private static final int DEFAULT_NULL_VALUE = (new int[1])[0]; private static final Random rnd = new Random(); private static final int POS_RANDOM_SHIFT_1; private static final int POS_RANDOM_SHIFT_2; private static final int STEP_RANDOM_SHIFT_1; private static final int STEP_RANDOM_SHIFT_2; static { POS_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11; POS_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21; STEP_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11; STEP_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21; } private long[] keys; private int[] values; private byte[] status; private int size; private int removedCount; private int mask; private boolean returnedNull; private final int hashSeed; public EzLongIntHashMap() { this(DEFAULT_CAPACITY); } public EzLongIntHashMap(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be non-negative"); } // Actually we need 4x more memory int length = 4 * Math.max(1, capacity); if ((length & (length - 1)) != 0) { length = Integer.highestOneBit(length) << 1; } // Length is a power of 2 now initEmptyTable(length); returnedNull = false; hashSeed = rnd.nextInt(); } private int getStartPos(int h) { h ^= hashSeed; h ^= (h >>> POS_RANDOM_SHIFT_1) ^ (h >>> POS_RANDOM_SHIFT_2); return h & mask; } private int getStep(int h) { h ^= hashSeed; h ^= (h >>> STEP_RANDOM_SHIFT_1) ^ (h >>> STEP_RANDOM_SHIFT_2); return ((h << 1) | 1) & mask; } public int size() { return size; } public boolean isEmpty() { return size == 0; } public boolean containsKey(long key) { final int keyHash = PrimitiveHashCalculator.getHash(key); int pos = getStartPos(keyHash); final int step = getStep(keyHash); for (; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && keys[pos] == key) { return true; } } return false; } public int get(long key) { final int keyHash = PrimitiveHashCalculator.getHash(key); int pos = getStartPos(keyHash); final int step = getStep(keyHash); for (; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && keys[pos] == key) { returnedNull = false; return values[pos]; } } returnedNull = true; return DEFAULT_NULL_VALUE; } public int put(long key, int value) { final int keyHash = PrimitiveHashCalculator.getHash(key); int pos = getStartPos(keyHash); final int step = getStep(keyHash); for (; status[pos] == FILLED; pos = (pos + step) & mask) { if (keys[pos] == key) { final int oldValue = values[pos]; values[pos] = value; returnedNull = false; return oldValue; } } if (status[pos] == FREE) { status[pos] = FILLED; keys[pos] = key; values[pos] = value; size++; if ((size + removedCount) * 2 > keys.length) { rebuild(keys.length * 2); // enlarge the table } returnedNull = true; return DEFAULT_NULL_VALUE; } final int removedPos = pos; for (pos = (pos + step) & mask; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && keys[pos] == key) { final int oldValue = values[pos]; values[pos] = value; returnedNull = false; return oldValue; } } status[removedPos] = FILLED; keys[removedPos] = key; values[removedPos] = value; size++; removedCount--; returnedNull = true; return DEFAULT_NULL_VALUE; } public int remove(long key) { final int keyHash = PrimitiveHashCalculator.getHash(key); int pos = getStartPos(keyHash); final int step = getStep(keyHash); for (; status[pos] != FREE; pos = (pos + step) & mask) { if (status[pos] == FILLED && keys[pos] == key) { final int removedValue = values[pos]; status[pos] = REMOVED; size--; removedCount++; if (keys.length > REBUILD_LENGTH_THRESHOLD) { if (8 * size <= keys.length) { rebuild(keys.length / 2); // compress the table } else if (size < removedCount) { rebuild(keys.length); // just rebuild the table } } returnedNull = false; return removedValue; } } returnedNull = true; return DEFAULT_NULL_VALUE; } public boolean returnedNull() { return returnedNull; } public void clear() { if (keys.length > REBUILD_LENGTH_THRESHOLD) { initEmptyTable(REBUILD_LENGTH_THRESHOLD); } else { Arrays.fill(status, FREE); size = 0; removedCount = 0; } } public long[] keys() { long[] result = new long[size]; for (int i = 0, j = 0; i < keys.length; i++) { if (status[i] == FILLED) { result[j++] = keys[i]; } } return result; } public int[] values() { int[] result = new int[size]; for (int i = 0, j = 0; i < values.length; i++) { if (status[i] == FILLED) { result[j++] = values[i]; } } return result; } private void rebuild(int newLength) { long[] oldKeys = keys; int[] oldValues = values; byte[] oldStatus = status; initEmptyTable(newLength); for (int i = 0; i < oldKeys.length; i++) { if (oldStatus[i] == FILLED) { put(oldKeys[i], oldValues[i]); } } } private void initEmptyTable(int length) { keys = new long[length]; values = new int[length]; status = new byte[length]; size = 0; removedCount = 0; mask = length - 1; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EzLongIntHashMap that = (EzLongIntHashMap) o; if (size != that.size) { return false; } for (int i = 0; i < keys.length; i++) { if (status[i] == FILLED) { int thatValue = that.get(keys[i]); if (that.returnedNull || thatValue != values[i]) { return false; } } } return true; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append('{'); for (int i = 0; i < keys.length; i++) { if (status[i] == FILLED) { if (sb.length() > 1) { sb.append(", "); } sb.append(keys[i]); sb.append('='); sb.append(values[i]); } } sb.append('}'); return sb.toString(); } } final class PrimitiveHashCalculator { private PrimitiveHashCalculator() { } public static int getHash(int x) { return x; } public static int getHash(long x) { return (int)x ^ (int)(x >>> 32); } }
JAVA
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
import java.util.TreeSet; import java.util.ArrayList; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.List; import java.io.BufferedReader; import java.util.Map; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.SortedSet; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { static class Cube implements Comparable<Cube> { int number; int x; int y; List<Cube> dependsOn = new ArrayList<>(1); List<Cube> dependents = new ArrayList<>(1); int numMusts = 0; public int compareTo(Cube o) { int z = numMusts - o.numMusts; if (z != 0) return z; return number - o.number; } } static final long MODULO = (long) (1e9 + 9); public void solve(int testNumber, InputReader in, PrintWriter out) { int m = in.nextInt(); Cube[] cubes = new Cube[m]; Map<Long, Cube> coordToCube = new HashMap<>(); for (int i = 0; i < m; ++i) { cubes[i] = new Cube(); cubes[i].number = i; cubes[i].x = in.nextInt(); cubes[i].y = in.nextInt(); long coord = cubes[i].x * (long) 3e9 + cubes[i].y; coordToCube.put(coord, cubes[i]); } for (Cube cube : cubes) { if (cube.y > 0) { for (int dx = -1; dx <= 1; ++dx) { long ncoord = (cube.x + dx) * (long) 3e9 + (cube.y - 1); Cube under = coordToCube.get(ncoord); if (under != null) { cube.dependsOn.add(under); under.dependents.add(cube); } } if (cube.dependsOn.isEmpty()) throw new RuntimeException(); if (cube.dependsOn.size() == 1) { ++cube.dependsOn.get(0).numMusts; } } } TreeSet<Cube> all = new TreeSet<>(); for (Cube cube : cubes) { all.add(cube); } long res = 0; Cube specialTail = new Cube(); specialTail.numMusts = 0; specialTail.number = m; for (int i = 0; i < m; ++i) { Cube toRemove; if (i % 2 == 0) { toRemove = all.headSet(specialTail).last(); } else { toRemove = all.first(); } if (toRemove.numMusts != 0) throw new RuntimeException(); all.remove(toRemove); res = (res * m + toRemove.number) % MODULO; for (Cube upper : toRemove.dependents) { upper.dependsOn.remove(toRemove); if (upper.dependsOn.size() == 1) { Cube newMust = upper.dependsOn.get(0); all.remove(newMust); ++newMust.numMusts; all.add(newMust); } } for (Cube lower : toRemove.dependsOn) { lower.dependents.remove(toRemove); if (toRemove.dependsOn.size() == 1) { all.remove(lower); --lower.numMusts; all.add(lower); } } } out.println(res); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
JAVA
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; const long long mod = 1e9 + 9; int n, start = 1; int a[4 * N], ans[N]; vector<int> jos[N], sus[N]; map<pair<int, int>, int> m; struct punct { int x, y; } poz[N]; void Update(int nod) { a[nod] = max(a[nod + nod], a[nod + nod + 1]); if (nod > 1) Update(nod / 2); } void check(int poz) { for (auto it : sus[poz]) { if (jos[it].size() == 1) { return; } } a[poz + start - 1] = 1; Update((poz + start - 1) / 2); } void REMOVE(int poz) { for (auto it : jos[poz]) { for (int i = 0; i < sus[it].size(); ++i) { if (sus[it][i] == poz) { sus[it].erase(sus[it].begin() + i); break; } } check(it); } for (auto it : sus[poz]) { for (int i = 0; i < jos[it].size(); ++i) { if (jos[it][i] == poz) { jos[it].erase(jos[it].begin() + i); break; } } if (jos[it].size() == 1) { a[jos[it][0] + start - 1] = 0; Update((jos[it][0] + start - 1) / 2); } } a[poz + start - 1] = 0; Update((poz + start - 1) / 2); } int find_left() { int nod = 1; while (nod < start) { if (a[nod + nod] >= a[nod + nod + 1]) nod = nod + nod; else nod = nod + nod + 1; } return nod; } int find_right() { int nod = 1; while (nod < start) { if (a[nod + nod + 1] >= a[nod + nod]) nod = nod + nod + 1; else nod = nod + nod; } return nod; } int main() { cin >> n; while (start < n) start <<= 1; for (int i = 1; i <= n; ++i) { cin >> poz[i].x >> poz[i].y; m[{poz[i].x, poz[i].y}] = i; } for (int i = 1; i <= n; ++i) { for (int j = -1; j <= 1; ++j) { if (m[{poz[i].x + j, poz[i].y - 1}]) { jos[i].push_back(m[{poz[i].x + j, poz[i].y - 1}]); sus[m[{poz[i].x + j, poz[i].y - 1}]].push_back(i); } } a[i + start - 1] = 1; Update((i + start - 1) / 2); } for (int i = 1; i <= n; ++i) { if (jos[i].size() == 1) { a[jos[i][0] + start - 1] = 0; Update((jos[i][0] + start - 1) / 2); } } int poz = 0; for (int i = 1; i <= n; ++i) { if (i & 1) { poz = find_right(); } else poz = find_left(); poz = poz - start + 1; REMOVE(poz); ans[i] = poz; } long long r = 0, P = 1; for (int i = n; i; --i) { r += ((long long)(ans[i] - 1) * P) % mod; r %= mod; P = (P * (long long)n) % mod; } cout << r; return 0; }
CPP
521_B. Cubes
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube. The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1). Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game. Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9. Input The first line contains number m (2 ≀ m ≀ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. Output In the only line print the answer to the problem. Examples Input 3 2 1 1 0 0 1 Output 19 Input 5 0 0 0 1 0 2 0 3 0 4 Output 2930
2
8
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.TreeSet; import java.util.ArrayList; import java.util.Map; import java.io.OutputStreamWriter; import java.io.OutputStream; import java.io.PrintStream; import java.io.IOException; import java.io.UncheckedIOException; import java.util.List; import java.io.Closeable; import java.util.Map.Entry; import java.io.Writer; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); BCubes solver = new BCubes(); solver.solve(1, in, out); out.close(); } } static class BCubes { TreeSet<Node> pq = new TreeSet<>(Comparator.comparingInt(x -> x.id)); Debug debug = new Debug(true); public void decreaseOutDeg(Node root, int mod) { if (root.removed) { return; } root.outdeg -= mod; if (root.outdeg == 1) { for (Node node : root.out) { if (node.removed) { continue; } node.indeg++; if (node.indeg == 1) { pq.remove(node); } } } } public void removeNode(Node root) { assert !root.removed; root.removed = true; if (root.outdeg == 1) { int cnt = 0; for (Node node : root.out) { if (node.removed) { continue; } cnt++; node.indeg--; if (node.indeg == 0) { pq.add(node); } } assert cnt == 1; } for (Node node : root.in) { decreaseOutDeg(node, 1); } } public void solve(int testNumber, FastInput in, FastOutput out) { int m = in.ri(); HashMap<Long, Node> nodes = new HashMap<>(); for (int i = 0; i < m; i++) { int x = in.ri(); int y = in.ri(); Node node = new Node(); node.id = i; long key = DigitUtils.asLong(x, y); nodes.put(key, node); } for (Map.Entry<Long, Node> entry : nodes.entrySet()) { int x = DigitUtils.highBit(entry.getKey()); int y = DigitUtils.lowBit(entry.getKey()); Node node = entry.getValue(); for (int i = -1; i <= 1; i++) { long key = DigitUtils.asLong(x + i, y - 1); Node exist = nodes.get(key); if (exist == null) { continue; } node.out.add(exist); node.outdeg++; exist.in.add(node); } pq.add(node); } for (Node node : nodes.values()) { decreaseOutDeg(node, 0); } int mod = (int) 1e9 + 9; long sum = 0; boolean max = true; while (!pq.isEmpty()) { Node head = max ? pq.pollLast() : pq.pollFirst(); debug.debug("head", head); sum = (sum * m + head.id) % mod; max = !max; removeNode(head); } out.println(sum); } } static class Debug { private boolean offline; private PrintStream out = System.err; static int[] empty = new int[0]; public Debug(boolean enable) { offline = enable && System.getSecurityManager() == null; } public Debug debug(String name, Object x) { return debug(name, x, empty); } public Debug debug(String name, Object x, int... indexes) { if (offline) { if (x == null || !x.getClass().isArray()) { out.append(name); for (int i : indexes) { out.printf("[%d]", i); } out.append("=").append("" + x); out.println(); } else { indexes = Arrays.copyOf(indexes, indexes.length + 1); if (x instanceof byte[]) { byte[] arr = (byte[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof short[]) { short[] arr = (short[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof boolean[]) { boolean[] arr = (boolean[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof char[]) { char[] arr = (char[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof int[]) { int[] arr = (int[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof float[]) { float[] arr = (float[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof double[]) { double[] arr = (double[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof long[]) { long[] arr = (long[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else { Object[] arr = (Object[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } } } return this; } } static class Node { int id; List<Node> out = new ArrayList<>(); List<Node> in = new ArrayList<>(); int outdeg; int indeg; boolean removed; public String toString() { return "" + id; } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private static final int THRESHOLD = 1 << 13; private final Writer os; private StringBuilder cache = new StringBuilder(THRESHOLD * 2); public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } private void afterWrite() { if (cache.length() < THRESHOLD) { return; } flush(); } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); afterWrite(); return this; } public FastOutput append(long c) { cache.append(c); afterWrite(); return this; } public FastOutput append(String c) { cache.append(c); afterWrite(); return this; } public FastOutput println(long c) { return append(c).println(); } public FastOutput println() { return append(System.lineSeparator()); } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int ri() { return readInt(); } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class DigitUtils { public static long INT_TO_LONG_MASK = (1L << 32) - 1; private DigitUtils() { } public static long asLong(int high, int low) { return (((long) high) << 32) | (((long) low) & INT_TO_LONG_MASK); } public static int highBit(long x) { return (int) (x >> 32); } public static int lowBit(long x) { return (int) x; } } }
JAVA