P5945
035966_L3
·
·
题解
本篇文章不讨论如何 DP(这不是本题重点),只讨论如何使用 C++ 手写值域超大(2^m,其中 m=LONG_DOUBLE_MAX)且不掉精度(long double 精度)的数据类型 Log。
考虑对一个数 x 存储 \log_2 x。
对于乘法和除法(2^a \times 2^b,a>b),直接上对数运算性质。
对于加法和减法(2^a+2^b,a>b),相差倍数太大(>2^{100})的可以直接返回较大数,否则用乘法分配率提取 2^b 后复原再相加。
```cpp
struct Log
{
long double x;
};
const long double ACC=100;
Log operator+(Log a,Log b)
{
if(a.x<b.x) swap(a,b);
if(a.x-b.x>ACC) return a;
long double res=b.x;
res+=log2l(powl(2,a.x-b.x)+1);
return (Log){res};
}
Log operator-(Log a,Log b)
{
if(a.x<b.x) exit(-1);
if(a.x-b.x>ACC) return a;
long double res=b.x;
res+=log2l(powl(2,a.x-b.x)-1);
return (Log){res};
}
Log operator*(Log a,Log b)
{
return (Log){a.x+b.x};
}
Log operator/(Log a,Log b)
{
return (Log){a.x-b.x};
}
void operator+=(Log&a,Log b)
{
a=a+b;
}
void operator-=(Log&a,Log b)
{
a=a-b;
}
void operator*=(Log&a,Log b)
{
a=a*b;
}
void operator/=(Log&a,Log b)
{
a=a/b;
}
const Log ZERO=(Log){-1e9};
```