有 n n n种糖果,其中第 i i i种有 a [ i ] a[i] a[i]个,一颗价格为 b [ i ] b[i] b[i],现在要把每种糖果装袋,假设第 i i i种装成 d [ i ] d[i] d[i]个每袋,这样就必须要保证 d [ i ] ∣ a [ i ] d[i]|a[i] d[i]∣a[i]的,每袋的单价 c [ i ] c[i] c[i]是价格总和 b [ i ] × d [ i ] b[i]\times d[i] b[i]×d[i]。现在把他们装袋后按原先的糖果顺序放置,一段袋装糖果的价格如果相同,那么他们就可以用一种价格牌标注,请问最少需要多少种价格牌就可以标注所有的袋装糖果?
假设一段 [ l , r ] [l,r] [l,r]的价格相同,即:
c [ l ] = c [ l + 1 ] = . . . = c [ r − 1 ] = c [ r ] = b [ l ] × d [ l ] = . . . = b [ r ] × d [ r ] c[l]=c[l+1]=...=c[r-1]=c[r]=b[l]\times d[l]=...=b[r]\times d[r] c[l]=c[l+1]=...=c[r−1]=c[r]=b[l]×d[l]=...=b[r]×d[r]
记 c o s t = c [ l ] = . . . = c [ r ] cost=c[l]=...=c[r] cost=c[l]=...=c[r]
那么每个 b [ i ] , i ∈ [ l , r ] b[i],i\in[l,r] b[i],i∈[l,r]都是 c o s t cost cost的因子,那么有
l c m ( b [ l ] , b [ l + 1 ] , . . . , b [ r − 1 ] , b [ r ] ) ∣ c o s t lcm(b[l],b[l+1],...,b[r-1],b[r])|cost lcm(b[l],b[l+1],...,b[r−1],b[r])∣cost
同时又需要 d [ i ] ∣ a [ i ] d[i]|a[i] d[i]∣a[i],那么有
d [ i ] ∣ a [ i ] ⇒ ( b [ i ] × d [ i ] ) ∣ ( a [ i ] × b [ i ] ) , i ∈ [ l , r ] d[i]|a[i]\Rightarrow (b[i]\times d[i])|(a[i]\times b[i]),i\in[l,r] d[i]∣a[i]⇒(b[i]×d[i])∣(a[i]×b[i]),i∈[l,r]
即
c o s t ∣ ( a [ i ] × b [ i ] ) , i ∈ [ l , r ] cost|(a[i]\times b[i]),i\in[l,r] cost∣(a[i]×b[i]),i∈[l,r]
即 c o s t cost cost要是所有的 a [ i ] × b [ i ] , i ∈ [ l , r ] a[i]\times b[i],i\in[l,r] a[i]×b[i],i∈[l,r]的因子,即
c o s t ∣ g c d ( a [ l ] × b [ l ] , . . . . , a [ r ] × b [ r ] ) cost|gcd(a[l]\times b[l],....,a[r]\times b[r]) cost∣gcd(a[l]×b[l],....,a[r]×b[r])
要满足 ( 2 ) ( 4 ) (2)(4) (2)(4)两个条件的物品就可以放置在一组了,要满足 ( 2 ) ( 4 ) (2)(4) (2)(4),只需要
l c m ( b [ l ] , b [ l + 1 ] , . . . , b [ r − 1 ] , b [ r ] ) ∣ g c d ( a [ l ] × b [ l ] , . . . . , a [ r ] × b [ r ] ) lcm(b[l],b[l+1],...,b[r-1],b[r])|gcd(a[l]\times b[l],....,a[r]\times b[r]) lcm(b[l],b[l+1],...,b[r−1],b[r])∣gcd(a[l]×b[l],....,a[r]×b[r])
贪心地与前面一个商品一起为一组的一定是最优结果,所以只需要双指针找满足 ( 2 ) ( 4 ) (2)(4) (2)(4)的段数即可。
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
using ll=long long;
const int N=2e5+5,inf=0x3fffffff;
const long long INF=0x3fffffffffffffff,mod=1e9+7;
int n,a[N],b[N];
vector<int>c[N];
void solve() {
cin>>n;
for(int i=1;i<=n;i++) {
cin>>a[i]>>b[i];
}
ll ans=1,lcm_val=b[1],gcd_val=1ll*a[1]*b[1];
for(int i=2;i<=n;i++) {
if(gcd(gcd_val,1ll*a[i]*b[i])%lcm(lcm_val,b[i])==0) {
gcd_val=gcd(gcd_val,1ll*a[i]*b[i]);
lcm_val=lcm(lcm_val,b[i]);
} else {
ans++;
gcd_val=1ll*a[i]*b[i];
lcm_val=b[i];
}
}
cout<<ans<<endl;
}
int main() {
#ifdef stdjudge
freopen("in.txt","r",stdin);
auto TimeFlagFirst=clock();
#endif
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int t; cin>>t;
while(t--) solve();
#ifdef stdjudge
freopen("CON","r",stdin);
std::cout<<std::endl<<"耗时:"<<std::clock()-TimeFlagFirst<<"ms"<<std::endl;
std::cout<<std::flush;
system("pause");
#endif
return 0;
}