📅  最后修改于: 2023-12-03 15:23:03.121000             🧑  作者: Mango
A certain street has $n$ houses built on either side exactly at equal distance. The distance between any two consecutive houses on a side is $d$. A cable has to be laid such that it starts from the first house on one side, crosses the street and ends at the first house on the other side. The cost of laying the cable on a unit length is Rs. $p$. Find the total cost of laying the cable.
For each test case, output a single line containing the total cost of laying the cable rounded off to two decimal places.
Input:
2
4 5 10
3 6 8
Output:
24.20
16.97
For the first test case, the total length of the cable is $2\sqrt{n^2 + d^2}$, which evaluates to 22.3607. Multiplying this by $p$ (10) gives us 223.607. Rounding this off to two decimal places gives us 223.61. However, we need to add the cost of the cable crossing the street, which is $\sqrt{2}d \cdot p$ (50.0 in this case). Adding this to the previous result gives us 273.61, which rounds off to 273.60.
For the second test case, the total length of the cable is $2\sqrt{n^2 + d^2}$, which evaluates to 19.6977. Multiplying this by $p$ (8) gives us 157.582. Rounding this off to two decimal places gives us 157.58. Adding the cost of the cable crossing the street, which is $\sqrt{2}d \cdot p$ (33.9411 in this case), gives us 191.52, which rounds off to 191.52.
import math
T = int(input())
for _ in range(T):
n, d, p = map(int, input().split())
length = 2 * math.sqrt(n**2 + d**2)
cost = length * p + math.sqrt(2) * d * p
print('%.2f' % round(cost, 2))
The above code reads the input and calculates the cost of laying the cable for each test case. It first reads the number of test cases and then loops through them. For each test case, it reads $n$, $d$, and $p$ and calculates the total length of the cable using the formula $2\sqrt{n^2 + d^2}$, where $n$ is the number of houses on one side, and $d$ is the distance between any two consecutive houses on a side.
It then multiplies this length by $p$ to get the cost of the cable without considering the cable crossing the street. To calculate the cost of the cable crossing the street, it multiplies $\sqrt{2}d$ (which is the diagonal distance between two houses across the street) by $p$ and adds it to the previous result. Finally, it rounds off the cost to two decimal places using the `round()` and string formatting functions.
The code uses the `math` module to calculate the square root of a number and the value of $\sqrt{2}$.