• 【hdu1573-X问题】拓展欧几里得-同余方程组


    http://acm.hdu.edu.cn/showproblem.php?pid=1573

    求小于等于N的正整数中有多少个X满足:

    X mod a0 = b0

    X mod a1 = b1

    ……

    X mod ai = bi

    (0<ai<=10)

    输入:第一行为一个正整数T,表示有T组测试数据。每组测试数据的第一行为两个正整数NM (0 < N <= 1000,000,000 , 0 < M <= 10),表示X小于等于N,数组ab中各有M个元素。接下来两行,每行各有M个正整数,分别为ab中的元素。

    输出:对应每一组输入,在独立一行中输出一个正整数,表示满足条件的X的个数。

    Sample Input

    3

    10 3

    1 2 3

    0 1 2

    100 7

    3 4 5 6 7 8 9

    1 2 3 4 5 6 7

    10000 10

    1 2 3 4 5 6 7 8 9 10

    0 1 2 3 4 5 6 7 8 9

    Sample Output

    1

    0

    3

    题解:同余方程组的裸题。尤其要注意的是所求的是正整数,也就是0的时候要特殊处理。

    #include<cstdio>
    #include<cstdlib>
    #include<cstring>
    #include<iostream>
    using namespace std;
    
    typedef long long LL;
    const LL M=20;
    LL a[M],b[M];
    
    LL exgcd(LL u,LL v,LL &x,LL &y)
    {
        if(v==0){ x=1;y=0;return u;}
        else
        {
            LL tx,ty;
            LL d=exgcd(v,u%v,tx,ty);
            x=ty;
            y=tx-(u/v)*ty;
            return d;
        }
    }
    
    int main()
    {
        // freopen("a.in","r",stdin);
        // freopen("a.out","w",stdout);
        LL T;
        scanf("%I64d",&T);
        while(T--)
        {
            LL n,m;
            bool bk=1;
            scanf("%I64d%I64d",&n,&m);
            for(LL i=1;i<=m;i++) scanf("%I64d",&a[i]);
            for(LL i=1;i<=m;i++) scanf("%I64d",&b[i]);
            LL A,B,C,g,x,tx,ty,a1,b1;
            a1=a[1],b1=b[1];
            for(LL i=2;i<=m;i++)
            {
                A=a1;B=a[i];C=b[i]-b1;
                g=exgcd(A,B,tx,ty);
                if(C%g) {bk=0;break;}
                x=((tx*C/g)%(B/g)+(B/g))%(B/g);
                b1=a1*x+b1;
                a1=a1/g*a[i];
            }
            if(bk)
            {
                /*
                得出不定方程a1x+b1=P后,x=0时b1=P。
                因为x可以等于0:ans=(n-b1)/a1+1;
                若P=0,则b1=x=0,不满足正整数,所以减去。
                */
                LL ans=0;
                if(n>=b1) ans=(n-b1)/a1+1;
                if(ans && b1==0) ans--;
                printf("%I64d
    ",ans);
            }
            else printf("0
    ");
        }
        return 0;
    }
    View Code
  • 相关阅读:
    单例
    Label自适应高度
    通知中心(以夜间模式为例)
    ios VFL屏幕自适应
    网络请求数据(同步POST,异步POST)
    linux 设备文件
    linux 文件存取 软硬联接的区别
    linux 磁盘管理与文件系统
    linux开机过程
    Build Antlr4 projects with eclipse java project template.
  • 原文地址:https://www.cnblogs.com/KonjakJuruo/p/5178467.html
Copyright © 2020-2023  润新知