UVa 10522 - Height to Area

链接

传送门

题意

给出三角形的三条高的长度,求三角形的面积。

思路

设三角形的三边为\(a\)\(b\)\(c\),对应的高分别为\(h_a\)\(h_b\)\(h_c\),三角形的面积为\(s\)

显然

\[a = \frac{2s}{h_a}, \space b = \frac{2s}{h_b}, \space c = \frac{2s}{h_c}\]

又因为

\[s = \sqrt{p \left( p - a \right) \left( p - b \right) \left( p - c \right)}\] \[p = \frac{1}{2} \left(a + b + c\right) = s\left(\frac{1}{h_a} + \frac{1}{h_b} + \frac{1}{h_c} \right)\]

化简得

\[s = \frac{1}{\sqrt{\left( \frac{1}{h_a} + \frac{1}{h_b} + \frac{1}{h_c} \right) \left( -\frac{1}{h_a} + \frac{1}{h_b} + \frac{1}{h_c} \right) \left( \frac{1}{h_a} - \frac{1}{h_b} + \frac{1}{h_c} \right) \left( \frac{1}{h_a} + \frac{1}{h_b} - \frac{1}{h_c} \right)}}\]

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;


int main() {
int t;
scanf("%d", &t);
while (t) {
double ha, hb, hc;
scanf("%lf%lf%lf", &ha, &hb, &hc);
if (ha == 0 || hb == 0 || hc == 0) {
puts("These are invalid inputs!");
--t;
} else {
double a = 1 / ha, b = 1 / hb, c = 1 / hc;
double p = a + b + c, pa = -a + b + c, pb = a - b + c, pc = a + b - c;
double s = p * pa * pb * pc;
if (s <= 0) {
puts("These are invalid inputs!");
--t;
} else {
printf("%.3f\n", 1 / sqrt(s));
}
}
}
return 0;
}