题目
题目链接
解题思路
- 对于总路程:
- 第1次:下落
h
h
h
- 第2次:反弹
(
h
/
2
)
(h/2)
(h/2) + 下落
(
h
/
2
)
(h/2)
(h/2)
- 第3次:反弹
(
h
/
4
)
(h/4)
(h/4) + 下落
(
h
/
4
)
(h/4)
(h/4)
- 第4次:反弹
(
h
/
8
)
(h/8)
(h/8) + 下落
(
h
/
8
)
(h/8)
(h/8)
- 第5次:反弹
(
h
/
16
)
(h/16)
(h/16) + 下落
(
h
/
16
)
(h/16)
(h/16)
- 第5次反弹高度就是初始高度除以2的5次方
def calculate_ball_path(height):
final_height = height / (2 ** 5)
total_distance = height
for i in range(4):
bounce_height = height / (2 ** (i + 1))
total_distance += bounce_height * 2
return total_distance, final_height
def main():
height = float(input())
distance, final_height = calculate_ball_path(height)
print(f"{distance}")
print(f"{final_height}")
if __name__ == "__main__":
main()
import java.util.Scanner;
public class Main {
public static double[] calculateBallPath(double height) {
double finalHeight = height / Math.pow(2, 5);
double totalDistance = height;
for (int i = 0; i < 4; i++) {
double bounceHeight = height / Math.pow(2, i + 1);
totalDistance += bounceHeight * 2;
}
return new double[]{totalDistance, finalHeight};
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double height = scanner.nextDouble();
double[] result = calculateBallPath(height);
System.out.println(result[0]);
System.out.println(result[1]);
scanner.close();
}
}
#include <iostream>
#include <cmath>
using namespace std;
pair<double, double> calculateBallPath(double height) {
double finalHeight = height / pow(2, 5);
double totalDistance = height;
for (int i = 0; i < 4; i++) {
double bounceHeight = height / pow(2, i + 1);
totalDistance += bounceHeight * 2;
}
return {totalDistance, finalHeight};
}
int main() {
double height;
cin >> height;
auto [distance, finalHeight] = calculateBallPath(height);
cout << distance << endl;
cout << finalHeight << endl;
return 0;
}
算法分析
- 算法:简单数学计算
- 时间复杂度:
O
(
1
)
\mathcal{O}(1)
O(1) - 只需固定次数的计算
- 空间复杂度:
O
(
1
)
\mathcal{O}(1)
O(1) - 只使用常数额外空间