アルゴリズムと数学 033

https://atcoder.jp/contests/math-and-algorithm/tasks/math_and_algorithm_ae

直線BC上の点は \vec{B} + t(\vec{C} - \vec{B})と表されるので、この点PとAを結んだ直線とBCが直交するなら、
 (\vec{B} + t(\vec{C} - \vec{B}) - \vec{A}) \cdot (\vec{C} - \vec{B}) = 0
 \displaystyle t = \frac{(\vec{A} - \vec{B}) \cdot (\vec{C} - \vec{B})}{\|\vec{C} - \vec{B}\|^2}

 0 \le t \le 1なら、点Pは線分BC上となり、Aから最短の点に、そうでなければBかCが最短の点になります。

// Distance
#![allow(non_snake_case)]

use std::ops::{Add, Sub};


//////////////////// library ////////////////////

fn read<T: std::str::FromStr>() -> T {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).ok();
    line.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>().split_whitespace()
            .map(|e| e.parse().ok().unwrap()).collect()
}


//////////////////// Point ////////////////////

#[derive(Clone, Copy)]
#[derive(Debug)]
struct Point {
    x: f64,
    y: f64,
}

impl Add for Point {
    type Output = Self;
    
    fn add(self, other: Self) -> Self {
        Self { x: self.x + other.x, y: self.y + other.y }
    }
}

impl Sub for Point {
    type Output = Self;
    
    fn sub(self, other: Self) -> Self {
        Self { x: self.x - other.x, y: self.y - other.y }
    }
}

impl Point {
    fn read() -> Point {
        let v = read_vec();
        Point { x: v[0], y: v[1] }
    }
    
    fn inner_product(v: &Point, w: &Point) -> f64 {
        v.x * w.x + v.y * w.y
    }
    
    fn mul(&self, a: f64) -> Point {
        Point { x: self.x * a, y: self.y * a }
    }
    
    fn mag(&self) -> f64 {
        Point::inner_product(self, self).sqrt()
    }
}


//////////////////// process ////////////////////

fn read_input() -> (Point, Point, Point) {
    let A = Point::read();
    let B = Point::read();
    let C = Point::read();
    (A, B, C)
}

fn f(A: Point, B: Point, C: Point) -> f64 {
    // (B + t(C - B) - A) * (C - B) = 0
    // t(C - B) * (C - B) = (A - B) * (C - B)
    let v1 = A - B;
    let v2 = C - B;
    let t = Point::inner_product(&v1, &v2) /
            Point::inner_product(&v2, &v2);
    let pt = if t < 0.0 { B }
             else if t < 1.0 { B + (C - B).mul(t) }
             else { C };
    (pt - A).mag()
}

fn main() {
    let (A, B, C) = read_input();
    println!("{}", f(A, B, C))
}