케이스를 잘 구분할 것
겹치는 지 확인하는 것보다, 겹치지 않는지 여부를 확인하는 것이 간단할 수 있다
A, B는 1차원 수직선상에서 구역청소를 진행한다.
A는 x = a 구역부터 x = b 구역까지 청소를 진행하고, B는 x = c 구역부터 x = d 구역까지 청소를 진행한다.
총 몇 구역이나 청소가 될지를 계산하라.
단, A, B가 청소하는 구역은 겹칠 수 있다.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
if ((a >= c && a <= d) || (b >= c && b <= d) || (c >= a && c <= b) || (d >= a && d <= b))
System.out.println(Math.max(a, Math.max(b, Math.max(c, d))) - Math.min(a, Math.min(b, Math.min(c, d))));
else
System.out.println(b - a + d - c);
}
}
import java.util.Scanner;
public class Main {
public static int a, b, c, d;
public static boolean intersecting(int x1, int x2, int x3, int x4) {
// 겹치지 않는 경우에 대한 처리를 먼저 진행합니다.
if(x2 < x3 || x4 < x1)
return false;
// 나머지는 전부 겹치는 경우라고 볼 수 있습니다.
else
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 입력:
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
d = sc.nextInt();
// 겹치는지를 확인합니다.
if(intersecting(a, b, c, d)) {
// 만약 겹치는 부분이 있다면,
// 두 구역들 중 가장 큰 구역에서 가장 작은 구역을 빼면
// 오늘 몇 구역이나 청소됐는지 알 수 있습니다.
System.out.print(Math.max(b, d) - Math.min(a, c));
}
else {
// 만약 겹치는 부분이 없다면,
// 두 구역들을 전부 더하면
// 오늘 몇 구역이나 청소됐는지 알 수 있습니다.
System.out.print((b - a) + (d - c));
}
}
}
Math.max(b, d) - Math.min(a, c)를 사용한다.b, d 중 최대값이 a, c 보다 크다는 것을 보장한다.a, c 중 최소값이 b, d 보다 작다는 것을 보장한다.