HDU 1573 中國剩餘定理(有不互質情況)

來源:互聯網
上載者:User

因為有不互質的情況,所以這道題不能直接用中國剩餘定理來求,

需要用最原始的方法,解線性模餘方程組來求,方法用到擴充歐幾裡德演算法....

#include <iostream>  
#include <cstdio>  
#include <cstring>  
using namespace std;  
typedef __int64 int64;  
int64 Mod;  
 
int64 gcd(int64 a, int64 b)  
{  
    if(b==0)  
        return a;  
    return gcd(b,a%b);  
}  
 
int64 Extend_Euclid(int64 a, int64 b, int64&x, int64& y)  
{  
    if(b==0)  
    {  
        x=1,y=0;  
        return a;  
    }  
    int64 d = Extend_Euclid(b,a%b,x,y);  
    int64 t = x;  
    x = y;  
    y = t - a/b*y;  
    return d;  
}  
 
//a在模n乘法下的逆元,沒有則返回-1  
int64 inv(int64 a, int64 n)  
{  
    int64 x,y;  
    int64 t = Extend_Euclid(a,n,x,y);  
    if(t != 1)  
        return -1;  
    return (x%n+n)%n;  
}  
 
//將兩個方程合并為一個  
bool merge(int64 a1, int64 n1, int64 a2, int64 n2, int64& a3, int64& n3)  
{  
    int64 d = gcd(n1,n2);  
    int64 c = a2-a1;  
    if(c%d)  
        return false;  
    c = (c%n2+n2)%n2;  
    c /= d;  
    n1 /= d;  
    n2 /= d;  
    c *= inv(n1,n2);  
    c %= n2;  
    c *= n1*d;  
    c += a1;  
    n3 = n1*n2*d;  
    a3 = (c%n3+n3)%n3;  
    return true;  
}  
 
//求模線性方程組x=ai(mod ni),ni可以不互質  
int64 China_Reminder2(int len, int64* a, int64* n)  
{  
    int64 a1=a[0],n1=n[0];  
    int64 a2,n2;  
    for(int i = 1; i < len; i++)  
    {  
        int64 aa,nn;  
        a2 = a[i],n2=n[i];  
        if(!merge(a1,n1,a2,n2,aa,nn))  
            return -1;  
        a1 = aa;  
        n1 = nn;  
    }  
    Mod = n1;  
    return (a1%n1+n1)%n1;  
}  
int64 a[30],b[30];  
int main()  
{  
    int t;
    scanf("%d",&t);
    while(t--){
         int64 n,m;
         int64 lcm=1;
         scanf("%I64d%I64d",&n,&m);
         for(int i = 0; i < m; i++){
             scanf("%I64d",&a[i]);
             lcm = lcm*a[i]/gcd(lcm,a[i]);
         }   
         for(int i=0; i<m; i++)
             scanf("%I64d",&b[i]);  
         int64 tall=0;
         if(China_Reminder2(m,b,a)==-1) printf("0\n");
         else{
             tall=China_Reminder2(m,b,a);
             if(tall>n) printf("0\n");
             else if(tall==0) printf("%I64d\n",n/lcm);
             else printf("%I64d\n",(n-tall)/lcm+1);
         }
    }  
    return 0;  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.