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}$。
同理对 $m$ 取模同样不影响结果。
所以我们在过程中可以任意取模,比每次约分都求一次 $\gcd$ 可以更高效地解决此问题。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#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--)
#define rep(i,s,e) for(int i=s;i<=e;i++)
#define per(i,s,e) for(int i=s;i>=e;i--)
namespace FastIO{
template<typename T>inline void read(T &x){
x=0;int f=1;char c=getchar();
for(;!isdigit(c);c=getchar())if(c=='-')f=-1;
for(;isdigit(c);c=getchar())x=(x<<1)+(x<<3)+(c^48);x*=f;
}
template<typename T,typename...Args>
inline void read(T &x,Args&...args){
read(x);
read(args...);
}
template<typename T>void print(T x){
if(x<0)x=-x,putchar('-');
if(x>9)print(x/10);
putchar((x%10)^48);
}
}
using namespace std;
using namespace FastIO;
const int N=1e4+7;
int T,n,a[N];
signed main(){
read(T);
while(T--){
read(n);
rep(i,1,n)read(a[i]);
int now=a[1]%a[2],flag=0;
rep(i,3,n){
now*=a[i];
if(now%a[2]==0){
flag=1;
break;
}
now%=a[2];
}
if(now%a[2]==0)flag=1;//特判只有两个数的情况
if(flag)puts("Yes");
else puts("No");
}
}