3203. Drawing
In a paper we define the rectangular coordinate system, a draw (x1,y1)
to (x2,y2)
the abscissa refers to the range from rectangular x1
to x2
ordinate from a range y1
to y2
be colored region between.
The following figure shows an example of drawing two rectangles.
The first is a rectangle (1,1)
to (4,4)
indicate green and purple.
The second rectangle is (2,3)
to (6,5
), shown in blue and purple.
FIG., A total 15
unit area is coated with a color, wherein the portion is coated with violet twice, but in the calculation of the area is calculated only once.
In the actual coloring process, all the rectangles are painted in a uniform color, and the different colors shown in the figure are only for convenience of illustration.
Given all the rectangles to be drawn, how many units of the area are colored.
Input format
The first line of input contains an integer n
, which indicates the number of rectangles to be drawn.
Next n
lines of 4
non-negative integer, respectively, and the ordinate abscissa represents the lower left corner of the rectangle to be drawn, and the abscissa and ordinate of the upper right corner.
Output format
Output an integer, indicating how many units of the area are painted.
Data range
1 ≤ n ≤ 100, 1≤n≤100,1≤n≤1 0 0 ,
0 ≤ abscissa, ordinate ≤ 100 0 ≤ abscissa, ordinate ≤ 1000≤Horizontal sitting standard , ordinate sitting standard≤100
Input sample:
2
1 1 4 4
2 3 6 5
Sample output:
15
Ideas:
As the title is given 0≤ 横坐标、纵坐标 ≤100
, the matrix is not large, even if the time complexity is O (n 2) O(n^2)O ( n2 ) Itis also acceptable, so we can create a100 × 100
two-dimensionalboolean
array ofsize, mark which grids are colored, and finally traverse the array to know how many grids are colored.
Note that this is where the correspondence relationship of the coordinates of the rectangle of the grid, as shown below: If the lower-left corner coordinates given (x1,y1)
are ( 0,0
), the coordinates of the upper right corner (x2 ,y2 )
is (2,2)
, the four lattice should be painted with a color (0,0)(0,1)(1,0)(1,1)
that we find the lattice The scope should be (x1,y1) ~ (x2 - 1,y2 -1)
, not (x1,y1) ~ (x2 ,y2 )
.
Java code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
boolean[][] state = new boolean[100][100];
//共有n个矩形
while(n-- != 0){
int x1 = sc.nextInt();
int y1 = sc.nextInt();
int x2 = sc.nextInt();
int y2 = sc.nextInt();
for(int i = x1;i < x2;i++){
for(int j = y1;j < y2;j++){
state[i][j] = true;
}
}
}
int res = 0;//计算有多少个格子被涂了颜色
for(int i = 0;i < 100;i++){
for(int j = 0;j < 100;j++){
if(state[i][j]){
res ++;
}
}
}
System.out.println(res);
}
}