题目描述
仅供参考
算法1
用总面积减去重复面积
Java 代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int N = 110;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int [][] arr = new int[N][N];
boolean [][] flag = new boolean[N][N];
for(int i = 0 ; i < n ;i++){
String[] s = br.readLine().split(" ");
for(int j = 0 ;j < 4;j++){
arr[i][j] = Integer.parseInt(s[j]);
}
}
int sum = 0;
for(int i = 0 ; i< n;i++){
int x1 = arr[i][0], y1 = arr[i][1];
int x2 = arr[i][2], y2 = arr[i][3];
sum += (x2 - x1) * (y2 - y1);
for(int j=x1; j<x2; j++) {
for(int k=y1; k<y2; k++) {
if(flag[j][k]) {
sum--;
}
flag[j][k] = true;
}
}
}
System.out.println(sum);
算法2
先标记 再统计
Java 代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int N = 110;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int [][] arr = new int[N][N];
boolean [][] flag = new boolean[N][N];
for(int i = 0 ; i < n ;i++){
String[] s = br.readLine().split(" ");
for(int j = 0 ;j < 4;j++){
arr[i][j] = Integer.parseInt(s[j]);
}
}
int sum = 0;
for(int i = 0 ; i< n;i++) {
int x1 = arr[i][0], y1 = arr[i][1];
int x2 = arr[i][2], y2 = arr[i][3];
for(int j=x1; j<x2; j++) {
for(int k=y1; k<y2; k++) {
flag[j][k] = true;
}
}
}
for(int i= 0 ;i<=100 ;i++){
for(int j = 0 ;j <=100 ;j++){
sum+= flag[i][j] ? 1 : 0;
}
}
System.out.println(sum);
}
}
算法2
在标记的同时统计
193ms,我提交的代码中最快的一次
Java 代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int N = 110;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int [][] arr = new int[N][N];
boolean [][] flag = new boolean[N][N];
for(int i = 0 ; i < n ;i++){
String[] s = br.readLine().split(" ");
for(int j = 0 ;j < 4;j++){
arr[i][j] = Integer.parseInt(s[j]);
}
}
int sum = 0;
for(int i = 0 ; i< n;i++) {
int x1 = arr[i][0], y1 = arr[i][1];
int x2 = arr[i][2], y2 = arr[i][3];
for(int j=x1; j<x2; j++) {
for(int k=y1; k<y2; k++) {
if (!flag[j][k]){
sum++;
flag[j][k] = true;
}
}
}
}
System.out.println(sum);
}
}