P3945 三体问题题解

· · 题解

题意

在三维空间中有 N 个可视为质点的天体,且已知引力常数,以及它们的质量,速度,位置。它们在万有引力下相互作用,且时间流动不连续,每 0.01s 刷新,问在一定时间后这 N 个天体各自的位置。

思路

这是一道大水题。

我们可以先用二维分析。

如图,有一质量为 m_1 千克,位于 A=(0,0) 的大天体和另一质量为 m_2 千克,位于 B=(x,y) 处的小天体。大天体对小天体的吸引力 \mathbf{F} 的大小为

|\mathbf{F}|=\frac{Gm_1m_2}{\mathbf{r}^2}

其中 \mathbf{r}=\overrightarrow{AB}。

由于万有引力是吸引力,所以 \mathbf{F} 的方向要与 \mathbf{r} 的方向相反,即

\mathbf{F}=-\frac{\mathbf{r}}{|\mathbf{r}|}\frac{Gm_1m_2}{|\mathbf{r}|^2}=-\frac{\mathbf{r}Gm_1m_2}{|\mathbf{r}|^3}

根据牛顿第二定律有 \mathbf{F}=m\mathbf{a},整理得 \mathbf{a}=\frac{\mathbf{F}}{m},易得其加速度的矢量表示为

\mathbf{a}=-\frac{\mathbf{r}Gm_1}{|\mathbf{r}|^3}

我们对加速度做正交分解,得

a_x=-\frac{|\mathbf{r}|Gm_1\cos\theta}{|\mathbf{r}|^3}=-\frac{|\mathbf{r}|Gm_1\frac{x}{|\mathbf{r}|}}{|\mathbf{r}|^3}=-\frac{Gm_1x}{|\mathbf{r}|^3} a_y=-\frac{|\mathbf{r}|Gm_1\sin\theta}{|\mathbf{r}|^3}=-\frac{|\mathbf{r}|Gm_1\frac{y}{|\mathbf{r}|}}{|\mathbf{r}|^3}=-\frac{Gm_1y}{|\mathbf{r}|^3}

这就是我们要的加速度公式,推广到三维后依旧适用。最后在每一帧中对于每个天体计算各个其他天体对它的合力产生的加速度,然后更新速度和位置即可。

代码

#include <bits/stdc++.h>
#define G 6.67408e-11 //引力常量
using namespace std;
typedef long double ld;
typedef long long ll;
struct body{ //每个天体的信息用结构体存储
    ld m, x, y, z, vx, vy, vz; //分别为质量,x坐标,y坐标,z坐标,x轴上的速度,y轴上的速度,z轴上的速度
};
ld dis(ld x1, ld y1, ld z1, ld x2, ld y2, ld z2){ //计算三维空间中两点距离
    return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2)); //勾股定理
}
body b[31]; //各个天体
ld gt = 0.01; // 不连续时间的每一帧的间隔
ld t; //模拟的时间
signed main(){
    ll n;
    cin >> n >> t;
    for (ll i = 1; i <= n; i++) cin >> b[i].x >> b[i].y >> b[i].z >> b[i].m >> b[i].vx >> b[i].vy >> b[i].vz;
    while (t > 0){
        t -= gt;
        for (ll i = 1; i <= n; i++){
            for (ll j = 1; j <= n; j++){
                //i号天体施加给j号天体万有引力
                if (i != j){ //防止计算时除0
                    ld r = dis(b[i].x, b[i].y, b[i].z, b[j].x, b[j].y, b[j].z);
                    ld a = G * b[j].m / r / r; //加速度的大小
                    ld ax = a * (b[j].x - b[i].x) / r; //公式代入
                    ld ay = a * (b[j].y - b[i].y) / r;
                    ld az = a * (b[j].z - b[i].z) / r;
                    b[i].vx += gt * ax; //更新速度
                    b[i].vy += gt * ay;
                    b[i].vz += gt * az;
                }
            }
        }
        for (ll i = 1; i <= n; i++){ //更新位置
            b[i].x += gt * b[i].vx;
            b[i].y += gt * b[i].vy;
            b[i].z += gt * b[i].vz;
        }
    }
    //输出
    for (ll i = 1; i <= n; i++) printf("%.12Lf %.12Lf %.12Lf\n", b[i].x, b[i].y, b[i].z);
}