【BZOJ2118】墨墨的等式 题解

2118: 墨墨的等式

Time Limit: 10 Sec Memory Limit: 259 MB

Description

墨墨突然对等式很感兴趣,他正在研究a1x1+a2y2+…+anxn=B存在非负整数解的条件,他要求你编写一个程序,给定N、{an}、以及B的取值范围,求出有多少B可以使等式存在非负整数解。

Input

输入的第一行包含3个正整数,分别表示N、BMin、BMax分别表示数列的长度、B的下界、B的上界。输入的第二行包含N个整数,即数列{an}的值。

Output

输出一个整数,表示有多少b可以使等式存在非负整数解。

Sample Input

2 5 10

3 5

Sample Output

5

HINT

对于100%的数据,N≤12,0≤ai≤5*10^5,1≤BMin≤BMax≤10^12。

Source

       这题总体来说并不难,很明显,如果存在一个合法的解 b ,那么 b + a [ i ] 也一定是合法的,故我们只要对于 a [ i ] 算出模其结果不同的合法的最小的数就能知道答案了。为了提高效率,我们取mn=min{ a [ i ] }。

       一维数组 d [ i ] 表示模 m n 等于 i 的最小的合法解,这可以用 d i j k s t r a s p f a 轻松求出;用 c a l c ( x ) 表示 [ 0 , x ] 中的合法解总数,则
c a l ( x ) = i = 0 m n 1 x d [ i ] m n + 1 ( x d [ i ] )

       最终答案即为:
c a l c ( b m a x ) c a l c ( b m i n 1 )


       注意忽略 a [ i ] 中的 0 !!!


       附上代码:

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstdlib>
using namespace std;
int n;
long long bl,br;
int a[13];
int mn=1e9;
int cnt;
long long d[500010];
bool inq[500010];
long long calc(long long x)
{
    long long res=0;
    for(int i=0;i<mn;i++)
    {
        if(d[i]>x)continue;
        res+=(x-d[i])/mn+1;
    } 
    return res;
}
int main()
{
    scanf("%d%lld%lld",&n,&bl,&br);
    for(int i=1;i<=n;i++)
    {
        int x;
        scanf("%d",&x);
        if(!x)continue;
        a[++cnt]=x;
        mn=min(mn,a[i]);
    }
    for(int i=1;i<mn;i++)d[i]=1e18;
    queue<int>q;
    q.push(0);
    inq[0]=true;
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        inq[x]=false;
        for(int i=1;i<=cnt;i++)
        {
            int y=(x+a[i])%mn;
            if(d[x]+a[i]<d[y])
            {
                d[y]=d[x]+a[i];
                if(!inq[y])
                {
                    inq[y]=true;
                    q.push(y); 
                }
            }
        }
    }
    printf("%lld",calc(br)-calc(bl-1));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42112677/article/details/80344951