解题思路
这道题要求根据已知的两个顶点坐标求正三角形的第三个顶点。关键点是:
- 给定正三角形的两个顶点坐标
- 需要找出第三个顶点的两个可能位置(在边的两侧)
- 每组数据有两个解(因为第三个点可以在边的两侧)
- 输出要保留两位小数,并按坐标大小排序
解题步骤:
- 对于给定的两个点
和
:
- 计算向量
- 利用正三角形的性质,第三个点
的坐标可以通过以下公式计算:
- 按坐标值从小到大排序输出两个解
代码
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
int n;
cin >> n;
for(int i = 0; i < n; i++) {
double x1, y1, x2, y2, x3, y3, x4, y4;
cin >> x1 >> y1 >> x2 >> y2;
// 计算向量AB
double dx = x2 - x1, dy = y2 - y1;
// 计算第一个可能的第三点坐标
x3 = x1 + 0.5*dx + sqrt(3)/2*dy;
y3 = y1 - sqrt(3)/2*dx + 0.5*dy;
// 计算第二个可能的第三点坐标
x4 = x1 + 0.5*dx - sqrt(3)/2*dy;
y4 = y1 + sqrt(3)/2*dx + 0.5*dy;
// 按坐标值从小到大输出
if(x3 < x4 || (x3 == x4 && y3 <= y4)) {
cout << fixed << setprecision(2)
<< x3 << " " << y3 << " "
<< x4 << " " << y4 << endl;
} else {
cout << fixed << setprecision(2)
<< x4 << " " << y4 << " "
<< x3 << " " << y3 << endl;
}
}
return 0;
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i = 0; i < n; i++) {
double x1 = sc.nextDouble();
double y1 = sc.nextDouble();
double x2 = sc.nextDouble();
double y2 = sc.nextDouble();
// 计算向量AB
double dx = x2 - x1;
double dy = y2 - y1;
// 计算两个可能的第三点坐标
double x3 = x1 + 0.5*dx + Math.sqrt(3)/2*dy;
double y3 = y1 - Math.sqrt(3)/2*dx + 0.5*dy;
double x4 = x1 + 0.5*dx - Math.sqrt(3)/2*dy;
double y4 = y1 + Math.sqrt(3)/2*dx + 0.5*dy;
// 按坐标值从小到大输出
if(x3 < x4 || (x3 == x4 && y3 <= y4)) {
System.out.printf("%.2f %.2f %.2f %.2f%n",
x3, y3, x4, y4);
} else {
System.out.printf("%.2f %.2f %.2f %.2f%n",
x4, y4, x3, y3);
}
}
}
}
import math
def find_third_points(x1, y1, x2, y2):
# 计算向量AB
dx = x2 - x1
dy = y2 - y1
# 计算两个可能的第三点坐标
x3 = x1 + 0.5*dx + math.sqrt(3)/2*dy
y3 = y1 - math.sqrt(3)/2*dx + 0.5*dy
x4 = x1 + 0.5*dx - math.sqrt(3)/2*dy
y4 = y1 + math.sqrt(3)/2*dx + 0.5*dy
# 按坐标值从小到大输出
if x3 < x4 or (x3 == x4 and y3 <= y4):
return x3, y3, x4, y4
else:
return x4, y4, x3, y3
n = int(input())
for _ in range(n):
x1, y1, x2, y2 = map(float, input().split())
x3, y3, x4, y4 = find_third_points(x1, y1, x2, y2)
print(f"{x3:.2f} {y3:.2f} {x4:.2f} {y4:.2f}")
算法及复杂度
- 算法:几何计算,使用正三角形的性质
- 时间复杂度:
,
为测试用例数量
- 空间复杂度:
,只需要常数额外空间