跳到正文

题解

题解:P2651 添加括号III

fan_xiaoyi约 4 分钟
原文

这是 2025年11月21日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟
题目
P2651

版本

  1. v2当前
  2. v1

P2651 添加括号III

思路

思路较为简单。因为要使得结果为整数,则只将 a2a_2 设为分母,其它均为分子。这里不做过多赘述,详见其他题解。

具体实现

aia_i 的范围非常大,显然不能直接累乘(除非你写高精度)。
注意到其它所有题解在约分时均使用了 gcd⁡(a,b)\gcd(a,b) 来约分,而它的最坏时间复杂度为 O(logmin⁡(a,b))O(log \min(a,b))。
这并不优秀,它使得整体的时间复杂度最坏为 O(T⋅n⋅logmin⁡(a,b))O(T\cdot n \cdot log\min(a,b)) 而我们有一种更优的做法,时间复杂度为 O(T⋅n)O(T\cdot n)。
原理很简单,在每一次累乘后直接将乘积对 a2a_2 取模即可。

证明

这题的结果由 (∏i=3nai)⋅a1(\prod_{i=3}^{n} a_i)\cdot a_1 能否整除 a2a_2 决定。
若我们在每一步后对乘积取模:
设当前乘积为 mm,要乘 ata_t,则分配率易证 m⋅at≡m⋅(at mod a2)(moda2)m\cdot a_t\equiv m\cdot (a_t\bmod a_2) \pmod {a_2}。
更系统化的:

∵m⋅at=m⋅(at mod a2+at−at mod a2)\because m\cdot a_t=m\cdot(a_t\bmod a_2+a_t-a_t\bmod a_2) ∴m⋅at=m⋅(at mod a2)+m⋅(at−at mod a2)\therefore m\cdot a_t=m\cdot (a_t\bmod a_2)+m\cdot (a_t-a_t\bmod a_2) ∵at−at mod a2≡0(moda2)\because a_t-a_t\bmod a_2\equiv0\pmod {a_2} ∴m⋅(at−at mod a2)≡0(moda2)\therefore m\cdot (a_t-a_t\bmod a_2)\equiv0\pmod {a_2} ∴m⋅at≡m⋅(at mod a2)(moda2)\therefore m\cdot a_t\equiv m\cdot (a_t\bmod a_2) \pmod {a_2}

即证毕。
同理对 mm 取模同样不影响结果。
所以我们在过程中可以任意取模,比每次约分都求一次 gcd⁡\gcd 可以更高效地解决此问题。

代码

C++
#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");
	}
}