置頂

我的 VPython 教學文件 (HackMD 版本)

VPython 教學文件目錄 安裝及測試 基本語法 等速度直線運動 自由落下 終端速度 水平抛射 使用For迴圈計算水平抛射資料 斜向抛射 圓周運動 簡諧運動 單擺 木塊彈簧系統分離 重力及簡諧 行星運動 相疊木塊 雙重簡諧運動 一維彈性碰撞 ...

熱門文章

2026年9月12日 星期六

ZeroJudge 解題筆記:r580.10432 - Polygon Inside A Circle

作者:王一哲
日期: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;
}


沒有留言:

張貼留言