바둑판 거리
가로·세로로만 움직일 수 있는 바둑판 모양 길에서 두 점 사이의 거리를 구한다.
첫 줄에 첫째 점의 좌표 x1 y1, 둘째 줄에 둘째 점의 좌표 x2 y2가 정수로 주어진다.
거리 |x1 − x2| + |y1 − y2|를 출력하라.
두 점이 같으면 0이다.
- 입력
- -100,000,000 ≤ x1, y1, x2, y2 ≤ 100,000,000
- 출력
- 거리 한 줄 (0 이상)
1 5 4 1
7
-2 -3 -7 -9
11
가로·세로로만 움직일 수 있는 바둑판 모양 길에서 두 점 사이의 거리를 구한다.
첫 줄에 첫째 점의 좌표 x1 y1, 둘째 줄에 둘째 점의 좌표 x2 y2가 정수로 주어진다.
거리 |x1 − x2| + |y1 − y2|를 출력하라.
두 점이 같으면 0이다.
1 5 4 1
7
-2 -3 -7 -9
11
실행하면 이 줄들이 차례로 input()·표준 입력으로 들어가요(실행 중에 묻지 않아요).
$ 준비됐어요
코드를 입력해 풀려면 PC에서 열어 주세요. 모바일에서는 문제와 풀이를 볼 수 있어요.
절댓값 함수 이름: Python abs()(내장), JS·TS Math.abs, Java Math.abs, C# Math.Abs, C++ std::abs(정수·실수 모두 오버로드), 크레이콘 수학.절댓값.
C는 타입마다 함수가 달라요 — int는 <stdlib.h>의 abs, long long은 llabs, double은 <math.h>의 fabs.
C에서 long long에 abs를 쓰면 int로 잘려요.
가장 흔한 함정은 차이를 먼저 더하고 절댓값을 한 번만 씌우는 것: |(x2 − x1) + (y2 − y1)|은 방향이 반대인 차이끼리 지워져서 첫 예시가 7이 아니라 1이 돼요.
절댓값은 차이마다 따로 씌워요.
(Java의 Math.abs(Integer.MIN_VALUE)는 넘쳐서 음수 그대로이고 C#의 Math.Abs(int.MinValue)는 OverflowException을 던지지만, 이 문제의 범위에서는 차이가 2억 이하라 괜찮아요.)
x1, y1 = map(int, input().split())x2, y2 = map(int, input().split())print(abs(x1 - x2) + abs(y1 - y2))const [x1, y1, x2, y2] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);console.log(Math.abs(x1 - x2) + Math.abs(y1 - y2));import { readFileSync } from "node:fs";const [x1, y1, x2, y2]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);console.log(Math.abs(x1 - x2) + Math.abs(y1 - y2));import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x1 = sc.nextInt(), y1 = sc.nextInt(); int x2 = sc.nextInt(), y2 = sc.nextInt(); System.out.println(Math.abs(x1 - x2) + Math.abs(y1 - y2)); }}using System; class Program{ static void Main() { string[] a = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); string[] b = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); int x1 = int.Parse(a[0]), y1 = int.Parse(a[1]); int x2 = int.Parse(b[0]), y2 = int.Parse(b[1]); Console.WriteLine(Math.Abs(x1 - x2) + Math.Abs(y1 - y2)); }}#include <cstdlib>#include <iostream> int main() { int x1, y1, x2, y2; std::cin >> x1 >> y1 >> x2 >> y2; std::cout << std::abs(x1 - x2) + std::abs(y1 - y2) << '\n';}#include <stdio.h>#include <stdlib.h> /* 정수 abs()는 stdlib.h, 실수 fabs()는 math.h */ int main(void) { int x1, y1, x2, y2; scanf("%d %d %d %d", &x1, &y1, &x2, &y2); printf("%d\n", abs(x1 - x2) + abs(y1 - y2)); return 0;}a = 콘솔.수들읽기();b = 콘솔.수들읽기();콘솔.쓰기(수학.절댓값(a[0] - b[0]) + 수학.절댓값(a[1] - b[1]));