Counting Squares_hdu_1264(矩阵).java
Counting Squares
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1086 Accepted Submission(s): 540
Problem Description
Your input is a series of rectangles, one per line. Each rectangle is specified as two points(X,Y) that specify the opposite corners of a rectangle. All coordinates will be integers in the range 0 to 100. For example, the line
5 8 7 10
specifies the rectangle who's corners are(5,8),(7,8),(7,10),(5,10).
If drawn on graph paper, that rectangle would cover four squares. Your job is to count the number of unit(i.e.,1*1) squares that are covered by any one of the rectangles given as input. Any square covered by more than one rectangle should only be counted once.
5 8 7 10
specifies the rectangle who's corners are(5,8),(7,8),(7,10),(5,10).
If drawn on graph paper, that rectangle would cover four squares. Your job is to count the number of unit(i.e.,1*1) squares that are covered by any one of the rectangles given as input. Any square covered by more than one rectangle should only be counted once.
Input
The input format is a series of lines, each containing 4 integers. Four -1's are used to separate problems, and four -2's are used to end the last problem. Otherwise, the numbers are the x-ycoordinates of two points that are opposite corners of a rectangle.
Output
Your output should be the number of squares covered by each set of rectangles. Each number should be printed on a separate line.
Sample Input
5 8 7 10
6 9 7 8
6 8 8 11
-1 -1 -1 -1
0 0 100 100
50 75 12 90
39 42 57 73
-2 -2 -2 -2
Sample Output
8
10000
Source
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner input=new Scanner(System.in); boolean ss=false; while(true){ boolean vis[][]=new boolean[101][101]; int a=input.nextInt(); int b=input.nextInt(); int c=input.nextInt(); int d=input.nextInt(); if(a==-2&&b==-2&&c==-2&&d==-2){ break; } boolean ok=false; int sum=0; while(!(a==-1&&b==-1&&c==-1&&d==-1)){ for(int i=Math.min(a, c)+1;i<=Math.max(a, c)&&!ok;i++){ for(int j=Math.min(b, d)+1;j<=Math.max(b, d);j++){ if(!vis[i][j]){ sum++; vis[i][j]=true; } } } if(sum==10000) ok=true; a=input.nextInt(); b=input.nextInt(); c=input.nextInt(); d=input.nextInt(); if(a==-2&&b==-2&&c==-2&&d==-2){ ss=true; break; } } System.out.println(sum); if(ss) break; } } }