SCU - 4532
a1∗b1+a2∗b2...+an∗bn=B
給定 a1...an , Bmax 、 Bmin
問有多少個B, Bmin<=B<=Bmax ,
使得 b1...bn 存在非負整數解
首先問題可以轉化為在區間 [0,Bmax] 有多少個 B滿足條件
如果能解決這個,原問題的用 [0,Bmax] 的答案減去 [0,Bmin−1] 的即可
接下來有一個很關鍵的步驟,也是這題的神來之筆
之是以說神,是因為目前我還沒深刻了解這麼做的道理 (2016.7.14)
将等式兩邊 moda1 (a序列中的任意一個數)
這樣使得 [0,Bmax] 中的數按 moda1 的餘數劃分成若幹個等價類
于是題目就轉化為了求每個等價類中最小的那個數
因為知道了最小的數 x ,那麼這個等價類的大小就可以用 Bmax−xa1+1來計算
然後把每個等價類的答案累加起來即為結果
設 dp[m]=b ,即 B%a1=m 這個等價類中,最小的那個數是 b
初始條件 dp[0]=0,在目前數 u 的基礎上不斷增加 ai,去更新 dp[(u+ai)%a1] 的狀态
轉移方程為 for i=2..n:dp[(u+ai)%a1]=min(dp[u]+ai)
由于這個 dp過程可能有環,是以采用 SPFA的方式進行轉移
#pragma comment(linker, "/STACK:102400000,102400000")
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cctype>
#include <map>
#include <set>
#include <queue>
using namespace std;
typedef pair<int,int> Pii;
typedef long long LL;
typedef unsigned long long ULL;
typedef double DBL;
typedef long double LDBL;
#define MST(a,b) memset(a,b,sizeof(a))
#define CLR(a) MST(a,0)
#define Sqr(a) ((a)*(a))
const int maxn=, maxa=+;
const LL INF=;
int N;
LL bmin, bmax;
LL A[maxn];
LL dp[maxa];
bool inq[maxa];
LL Get(LL,LL,int);
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif
int T;
scanf("%d", &T);
for(int ck=; ck<=T; ck++)
{
scanf("%d%lld%lld", &N, &bmin, &bmax);
for(int i=; i<=N; i++) scanf("%lld\n", &A[i]);
sort(A+, A++N);
if(A[]==)
{
puts("0");
continue;
}
MST(dp,);
CLR(inq);
dp[]=;
inq[]=;
queue<LL> que;
que.push();
while(que.size())
{
LL u=que.front(); que.pop();
for(int i=; i<=N; i++)
{
LL v = (u+A[i])%A[];
if(dp[v] > dp[u]+A[i])
{
dp[v] = dp[u]+A[i];
if(!inq[v])
{
inq[v]=;
que.push(v);
}
}
}
inq[u]=;
}
// for(int i=0; i<A[1]; i++) printf("%lld ", dp[i]); puts("");
LL ans=;
for(int i=; i<A[]; i++)
{
ans += Get(bmax,dp[i],A[]) - Get(bmin-,dp[i],A[]);
}
cout << ans << '\n';
}
return ;
}
LL Get(LL R, LL L, int r)
{
if(R<L) return ;
return (R-L)/r+;
}