碁盤の目の距離
縦横にしか動けない碁盤の目のような道で、二点の間の距離を求める。
一行目に一つ目の点の座標 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()・標準入力に渡されます(実行中に入力を求めません)。
$ 準備完了
コードを入力して解くにはパソコンで開いてください。モバイルでは問題と解答を見られます。
絶対値の関数名:Python abs()(組み込み)、JS・TS Math.abs、Java Math.abs、C# Math.Abs、C++ std::abs(整数・実数ともオーバーロード)、Craykon 数学.絶対値。
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]));