看了下题意,大致就是取交集,先把其中两个点固定,有四种情况,一开始是只做了一个for循环,得分只有十分,发现是只考虑小w和小H输入同一行的情况,没有考虑跨行(不大会说)。
package com.example.administrator.test.ccf;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author kyp
* @time 2019/7/23
* @description 买菜 取交集
*/
public class _20180902 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[][] h = new int[n][2];
int[][] w = new int[n][2];
for (int i = 0; i < n; i++) {
String content = br.readLine();
String[] c = content.split(" ");
h[i][0] = Integer.parseInt(c[0]);
h[i][1] = Integer.parseInt(c[1]);
}
for (int i = 0; i < n; i++) {
String content = br.readLine();
String[] c = content.split(" ");
w[i][0] = Integer.parseInt(c[0]);
w[i][1] = Integer.parseInt(c[1]);
}
br.close();
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j=0;j<n;j++){
sum += calc(h[i][0], h[i][1], w[j][0], w[j][1]);
}
}
System.out.println(sum);
}
public static int calc(int a, int b, int c, int d) {
int sum = 0;
if (a <= c && b <= d && c <=b) {
sum = b - c;
} else if (c <= a && a <= d && d <= b) {
sum = d - a;
} else if (c <= a && b <= d) {
sum = b - a;
} else if (a <= c && d <= b) {
sum = d - c;
}
return sum;
}
}
然后只是暴力解法,感觉还是有得优化的,在网上看到一个很巧秒的解法(https://blog.csdn.net/AivenZhong/article/details/83343579)
思路是这样的
import java.util.Scanner;
public class _20131201{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] t = new int[1000000];
int count = 0;
for (int i = 0; i < n * 2; i++) {
int a = input.nextInt();
int b = input.nextInt();
for (int j = a; j < b; j++)
t[j]++;
}
for (int i : t)
if (i > 1)
count++;
System.out.println(count);
}
}
凡是为2的都是重合的时间段,因为使用IO操作,画的时间与空间反而比两个for高