CCF 历年真题之画图(_1409_2_Drawing)参考答案
问题描述
试题编 号: | 201409-2 |
试题名称: | 画图 |
时间限制: | 1.0s |
内存限制: | 256.0MB |
问题描述: |
问题描述
在一个定义了直角坐标系的纸上,画一个(x1,y1)到(x2,y2)的矩形指将横坐标范围从x1到x2,纵坐标范围从y1到y2之间的区域涂上颜色。
下图给出了一个画了两个矩形的例子。第一个矩形是(1,1) 到(4, 4),用绿色和紫色表示。第二个矩形是(2, 3)到(6, 5),用蓝色和紫色表示。图中,一共有15个单位的面积被涂上颜色,其中紫色部分被涂了两次,但在计算面积时只计算一次。在实际的涂色过程中,所有的矩形都涂成统一的颜色,图中显示不同颜色仅为说明方便。 给出所有要画的矩形,请问总共有多少个单位的面积被涂上颜色。
输入格式
输入的第一行包含一个整数n,表示要画的矩形的个数。
接下来n行,每行4个非负整数,分别表示要画的矩形的左下角的横坐标与纵坐标,以及右上角的横坐标与纵坐标。
输出格式
输出一个整数,表示有多少个单位的面积被涂上颜色。
样例输入
2
1 1 4 4 2 3 6 5
样例输出
15
评测用例规模与约定
1<=n<=100,0<=横坐标、纵坐标<=100。
|
參考代碼:
import java.util.Scanner;
public class _1409_2_Drawing {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int n=input.nextInt();
int i,j,k,result=0;
int[][] coordinate=new int[101][101];
Rectangle[] rectangle=new Rectangle[n];
/* 記錄 n 個矩形 的 x1,y1,x2,y2 坐標*/
for( i=0;i<n;i++){
rectangle[i]=new Rectangle(input.nextInt(),input.nextInt(),input.nextInt(),input.nextInt());
}
/* 在坐標系上把矩形内的坐標記為 1*/
for(i=0;i<n;i++){
for(j=0;j<rectangle[i].getHeight();j++){
for(k=0;k<rectangle[i].getWidth();k++){
/* 從第一個矩形開始在坐標系上把矩形内的坐標都記為 1
* rectangle[i].getX1()+j ---> 從第 i 個矩形的 x1 坐標開始,到第 i 個矩形的 x2 坐標結束
* rectangle[i].getY1()+k ---> 從第 i 個矩形的 y1 坐標開始,到第 i 個矩形的 y2 坐標結束
*/
coordinate[rectangle[i].getX1()+j][rectangle[i].getY1()+k]=1;
}
}
}
/* 統計 1 的個數*/
for(i=0;i<101;i++){
for(j=0;j<101;j++){
if(coordinate[i][j]==1){
result++;
}
}
}
System.out.println(result);
input.close();
}
}
/* 自定義矩形的屬性:x1,y1,x2,y2,width,height */
class Rectangle{
private int x1,y1,x2,y2;
private int width,height;
public int getX1() {
return x1;
}
public void setX1(int x1) {
this.x1 = x1;
}
public int getY1() {
return y1;
}
public void setY1(int y1) {
this.y1 = y1;
}
public int getX2() {
return x2;
}
public void setX2(int x2) {
this.x2 = x2;
}
public int getY2() {
return y2;
}
public void setY2(int y2) {
this.y2 = y2;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public Rectangle() {
super();
// TODO Auto-generated constructor stub
}
public Rectangle(int x1, int y1, int x2, int y2) {
super();
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.width=Math.abs(this.y2-this.y1);
this.height=Math.abs(this.x2-this.x1);
}
}
提交可通過: