可以知道[a,b]能覆盖的区间是[a,b],[2a,2b],[3a,3b]...[ka,kb]...等等,先求出这些区间何时交在一起即k*b>=(k+1)*a-1,然后再细致一点分类讨论即可。
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef long long ll;
inline char nc(){
static char buf[100000],*p1=buf,*p2=buf;
if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }
return *p1++;
}
inline void read(ll &x){
char c=nc(),b=1;
for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc());
}
ll A,B,S,T,K,Ans;
inline ll Sum(ll l,ll r){
if (l>r) return 0;
if ((l+r)&1) return (r-l+1)/2*(l+r);
return (l+r)/2*(r-l+1);
}
int main(){
ll Q,pos,pos2;
freopen("t.in","r",stdin);
freopen("t.out","w",stdout);
read(Q);
while (Q--){
read(A); read(B); read(S); read(T); S=max(S,A);
K=(B-1)/(B-A)+1; K=max(K-1,1LL); Ans=0;
if (S>=K*A){
Ans=T-S+1;
}else if (T>=K*A){
pos=S/A;
if (S<=pos*B)
Ans+=pos*B-S+1;
if (pos+1<=K-1)
Ans+=Sum(pos+1,K-1)*(B-A)+(K-1-pos-1+1);
Ans+=T-K*A+1;
}else{
pos=S/A; pos2=T/A;
if (S<=pos*B)
Ans+=pos*B-S+1;
if (pos+1<=pos2-1) Ans+=Sum(pos+1,pos2-1)*(B-A)+(pos2-1-pos-1+1);
Ans+=T-pos2*A+1;
}
printf("%lld\n",Ans);
}
return 0;
}