日期:2026年9月12日
ZeroJudge 題目連結:r580.10432 - Polygon Inside A Circle
解題想法
題目有多筆測資。每一列有 2 個數字,分別代表半徑 $r$,於圓內畫出正 $n$ 邊形,題目要回傳這個正 $n$ 邊形的面積。這題考數學,可以將正 $n$ 邊形以圓心為頂點,分割成 $n$ 個等腰三角形,等長的兩個邊之間的夾角為 $\theta = 2 \pi / n$,三角形面積為 $$ a = \frac{1}{2} r^2 \sin \theta $$ 因此正 $n$ 邊形面積為 $area = a \times n$。
Python 程式碼
使用時間約為 13 ms,記憶體約為 9.8 MB,通過測試。
def solve():
import sys, math
def get_tokens():
for line in sys.stdin:
for part in line.split():
yield float(part)
tokens = get_tokens()
while True:
try:
r = next(tokens)
n = next(tokens)
except StopIteration:
break
theta = 2.0 * math.pi / n
area = 0.5 * r * r * math.sin(theta) * n
sys.stdout.write(f"{area:.3f}\n")
if __name__ == "__main__":
solve()
C++ 程式碼
使用時間約為 1 ms,記憶體約為 3.9 MB,通過測試。
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
double r, n, pi = acos(-1);
while(cin >> r >> n) {
double theta = 2.0 * pi / n;
double area = 0.5 * r * r * sin(theta) * n;
cout << fixed << setprecision(3) << area << "\n";
}
return 0;
}
使用時間約為 1 ms,記憶體約為 2 MB,通過測試。
#include <cstdio>
#include <cmath>
int main() {
double r, n, pi = acos(-1);
while(scanf("%lf %lf", &r, &n) != EOF) {
double theta = 2.0 * pi / n;
double area = 0.5 * r * r * sin(theta) * n;
printf("%.3lf\n", area);
}
return 0;
}
C 語言程式碼
使用時間約為 1 ms,記憶體約為 2.1 MB,通過測試。
#include <stdio.h>
#include <math.h>
int main() {
double r, n, pi = acos(-1);
while(scanf("%lf %lf", &r, &n) != EOF) {
double theta = 2.0 * pi / n;
double area = 0.5 * r * r * sin(theta) * n;
printf("%.3lf\n", area);
}
return 0;
}
沒有留言:
張貼留言