牛客网 2018校招真题 百度 正三角形的顶点位置

Description

牛客网 2018校招真题 正三角形的顶点位置

Solving Ideas

double dx = x2 - x1, dy = y2 - y1;
考虑dx != 0 && dy != 0的情况:
AE 垂直于 OE,当斜率 k < 0 时,有
牛客网 2018校招真题 百度 正三角形的顶点位置_第1张图片
其中, ∵ ∠ O A E = ∠ B C D ∴ s i n ∠ O A E = s i n ∠ B C D = B D B C \because \angle OAE = \angle BCD \\ \therefore sin\angle OAE = sin\angle BCD = \frac{BD}{BC} OAE=BCDsinOAE=sinBCD=BCBD
(k > 0时类似)

Solution

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author wylu
 */
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());

        while (t-- != 0) {
            String[] strs = br.readLine().split(" ");
            double x1 = Double.parseDouble(strs[0]), y1 = Double.parseDouble(strs[1]);
            double x2 = Double.parseDouble(strs[2]), y2 = Double.parseDouble(strs[3]);

            double dx = x2 - x1, dy = y2 - y1;
            double edgeLen = Math.sqrt(dx * dx + dy * dy);
            double height = Math.sqrt(3) / 2.0 * edgeLen;

            double resX1, resY1, resX2, resY2;
            if (dx == 0) {
                resX1 = x1 - height;
                resX2 = x1 + height;
                resY1 = (y1 + y2) / 2.0;
                resY2 = resY1;
            } else if (dy == 0) {
                resX1 = (x1 + x2) / 2.0;
                resX2 = resX1;
                resY1 = y1 - height;
                resY2 = y1 + height;
            } else {
                double midX = (x1 + x2) / 2.0, midY = (y1 + y2) / 2.0;
                double sine = Math.abs(dy / edgeLen), k = dy / dx;
                double ox = height * sine, oy = ox / k;
                resX1 = midX - ox;
                resY1 = midY + oy;
                resX2 = midX + ox;
                resY2 = midY - oy;
            }
            System.out.printf("%.2f %.2f %.2f %.2f\n", resX1, resY1, resX2, resY2);
        }
    }
}

你可能感兴趣的:(NowCoder)