题目链接: BZOJ - 1502
题目分析
这是我做的第一道 Simpson 积分的题目。Simpson 积分是一种用 (fl + 4*fmid + fr) / 6 * (r - l) 来拟合 fl...fr 的方法。自适应 Simpson 的自适应指的是,如果分成左右两端分别 Simpson 的和与对整段 Simpson 的差值不超过一个 Eps,那么就接受这个值,否则递归下去求两段的 Simpson 值。
代码
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm> using namespace std; typedef double LF; const LF Eps = 1e-; inline LF gmin(LF a, LF b) {return a < b ? a : b;}
inline LF gmax(LF a, LF b) {return a > b ? a : b;}
inline LF Sqr(LF x) {return x * x;} const int MaxN = + ; int n; LF Alpha, talpha, Ht, Lp, Rp, Ans;
LF A[MaxN], P[MaxN], Rad[MaxN], Ls[MaxN], Rs[MaxN], Lh[MaxN], Rh[MaxN]; inline LF f(LF x)
{
LF ret = 0.0;
for (int i = ; i <= n; ++i)
{
if (fabs(x - P[i]) < Rad[i]) ret = gmax(ret, sqrt(Sqr(Rad[i]) - Sqr(x - P[i])));
if (x > Ls[i] && x < Rs[i]) ret = gmax(ret, Lh[i] + (Rh[i] - Lh[i]) * (x - Ls[i]) / (Rs[i] - Ls[i]));
}
return ret;
} inline LF Simpson(LF l, LF r, LF fl, LF fmid, LF fr)
{
return (fl + fmid * 4.0 + fr) / 6.0 * (r - l);
} LF RSimpson(LF l, LF r, LF fl, LF fmid, LF fr)
{
LF mid, p, q, x, y, z;
mid = (l + r) / 2.0;
p = f((l + mid) / 2.0);
q = f((mid + r) / 2.0);
x = Simpson(l, r, fl, fmid, fr);
y = Simpson(l, mid, fl, p, fmid);
z = Simpson(mid, r, fmid, q, fr);
if (fabs(x - y - z) < Eps) return y + z;
else return RSimpson(l, mid, fl, p, fmid) + RSimpson(mid, r, fmid, q, fr);
} int main()
{
scanf("%d%lf", &n, &Alpha);
talpha = tan(Alpha);
Ht = 0.0;
for (int i = ; i <= n + ; ++i)
{
scanf("%lf", &A[i]);
Ht += A[i];
P[i] = Ht / talpha;
}
Lp = P[]; Rp = P[n + ];
for (int i = ; i <= n; ++i)
{
scanf("%lf", &Rad[i]);
Lp = gmin(Lp, P[i] - Rad[i]);
Rp = gmax(Rp, P[i] + Rad[i]);
}
Rad[n + ] = 0.0;
for (int i = ; i <= n; ++i)
{
if (P[i + ] - P[i] > fabs(Rad[i + ] - Rad[i]))
{
Ls[i] = P[i] + Rad[i] * (Rad[i] - Rad[i + ]) / (P[i + ] - P[i]);
Rs[i] = P[i + ] + Rad[i + ] * (Rad[i] - Rad[i + ]) / (P[i + ] - P[i]);
Lh[i] = sqrt(Sqr(Rad[i]) - Sqr(Ls[i] - P[i]));
Rh[i] = sqrt(Sqr(Rad[i + ]) - Sqr(Rs[i] - P[i + ]));
}
else
{
Ls[i] = -;
Rs[i] = -;
}
}
Ans = RSimpson(Lp, Rp, f(Lp), f((Lp + Rp) / 2.0), f(Rp)) * ;
printf("%.2lf\n", Ans);
return ;
}