版本比较
题解:P2651 添加括号III
正文
增加 9 行删除 9 行
12345678910111213141516171819202122232425262728293043 行未改动# P2651 添加括号III## 思路思路较为简单。因为要使得结果为整数,则只将 $a_2$ 设为分母,其它均为分子。这里不做过多赘述,详见其他题解。## 具体实现$a_i$ 的范围非常大,显然不能直接累乘(除非你写高精度)。注意到其它所有题解在约分时均使用了 $\gcd(a,b)$ 来约分,而它的最坏时间复杂度为 $O(log \min(a,b))$。这并不优秀,它使得整体的时间复杂度最坏为 $O(T\cdot n \cdot log\min(a,b))$ 而我们有一种更优的做法,时间复杂度为 $O(T\cdot n)$。原理很简单,在每一次累乘后直接将乘积对 $a_2$ 取模即可。## 证明这题的结果由 $(\prod_{i=3}^{n} a_i)\cdot a_1$ 能否整除 $a_2$ 决定。若我们在每一步后对乘积取模:设当前乘积为 $m$,要乘 $a_t$,则分配率易证 $m\cdot a_t\equiv m\cdot (a_t\bmod a_2) \pmod {a_2}$。更系统化的:$$\because m\cdot a_t=m\cdot(a_t\bmod a_2+a_t-a_t\bmod a_2)$$$$\therefore m\cdot a_t=m\cdot (a_t\bmod a_2)+m\cdot (a_t-a_t\bmod a_2)$$$$\because a_t-a_t\bmod a_2\equiv0\pmod {a_2}$$$$\therefore m\cdot (a_t-a_t\bmod a_2)\equiv0\pmod {a_2}$$$$\therefore m\cdot a_t\equiv m\cdot (a_t\bmod a_2) \pmod {a_2}$$即证毕。同理对 $m$ 取模同样不影响结果。所以我们在过程中可以任意取模,比每次约分都求一次 $\gcd$ 可以更高效地解决此问题。## 代码```cpp#include<bits/stdc++.h>#define fir first#define sec second#define int long long#define pii pair<int,int>#define fep(i,s,e) for(int i=s;i<e;i++)#define pef(i,s,e) for(int i=s;i>e;i--)43 行未改动12345678910111213141516171819202122232425262728293043 行未改动# P2651 添加括号III## 思路思路较为简单。因为要使得结果为整数,则只将 $a_2$ 设为分母,其它均为分子。这里不做过多赘述,详见其他题解。## 具体实现$a_i$ 的范围非常大,显然不能直接累乘(除非你写高精度)。注意到其它所有题解在约分时均使用了 $\gcd(a,b)$ 来约分,而它的最坏时间复杂度为 $O(log \min(a,b))$。这并不优秀,它使得整体的时间复杂度最坏为 $O(T\cdot n \cdot log\min(a,b))$ 而我们有一种更优的做法,时间复杂度为 $O(T\cdot n)$。原理很简单,在每一次累乘后直接将乘积对 $a_2$ 取模即可。## 证明这题的结果由 $(\prod_{i=3}^{n} a_i)\cdot a_1$ 能否整除 $a_2$ 决定。若我们在每一步后对乘积取模:设当前乘积为 $m$,要乘 $a_t$,则分配率易证 $m\cdot a_t\equiv m\cdot (a_t\bmod a_2) \pmod {a_2}$。更系统化的:$$\because m\cdot a_t=m\cdot(a_t\bmod a_2+a_t-a_t\bmod a_2)$$$$\therefore m\cdot a_t=m\cdot (a_t\bmod a_2)+m\cdot (a_t-a_t\bmod a_2)$$$$\because a_t-a_t\bmod a_2\equiv0\pmod {a_2}$$$$\therefore m\cdot (a_t-a_t\bmod a_2)\equiv0\pmod {a_2}$$$$\therefore m\cdot a_t\equiv m\cdot (a_t\bmod a_2) \pmod {a_2}$$即证毕。同理对 $m$ 取模同样不影响结果。所以我们在过程中可以任意取模,比每次约分都求一次 $\gcd$ 可以更高效地解决此问题。## 代码```cpp#include<bits/stdc++.h>#define fir first#define sec second#define int long long#define pii pair<int,int>#define fep(i,s,e) for(int i=s;i<e;i++)#define pef(i,s,e) for(int i=s;i>e;i--)43 行未改动