【poj2891】Strange Way to Express Integers(线性同余方程组)

Description

Elina is reading a book written by Rujia Liu, which introduces a strange way to express non-negative integers. The way is described as following:
Choose k different positive integers a1, a2, …, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1, a2, …, ak are properly chosen, m can be determined, then the pairs (ai, ri) can be used to express m.
“It is easy to calculate the pairs from m, ” said Elina. “But how can I find m from the pairs?”
Since Elina is new to programming, this problem is too difficult for her. Can you help her?

Input

The input contains multiple test cases. Each test cases consists of some lines.

Line 1: Contains the integer k.
Lines 2 ~ k + 1: Each contains a pair of integers ai, ri (1 ≤ i ≤ k).

Output

Output the non-negative integer m on a separate line for each test case. If there are multiple possible values, output the smallest one. If there are no possible values, output -1.

题解:

题意就是是否存在满足m≡ri (mod ai) (1<=i<=k),求满足条件的m的最小正整数。如果没有就输出-1。
但是这里m和ai不互素。所以只能用线性同余方程组来求解。
线性同余方程组是中国剩余定理的进阶
不懂线性同余方程组的点这里,啦啦啦

代码:

#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
typedef long long LL;
const int MAX_N=1e5+500;
LL A[MAX_N],B[MAX_N],M[MAX_N];
int n;
LL gcd(LL x,LL y)
{
    if(y==0) return x;
    else return gcd(y,x%y);
}
void extgcd(LL a,LL b,LL &x,LL &y)
{
    if(b!=0)
    {
        extgcd(b,a%b,y,x);
        y-=(a/b)*x;
    }
    else
    {
        x=1; y=0;
    }
}
LL inv(LL a,LL m)
{
    LL x,y;
    extgcd(a,m,x,y);
    return (m+x%m)%m;
}
pair<LL,LL> linear()
{
    LL x=0,m=1;
    for(int i=0;i<n;i++)
    {
        LL a=A[i]*m,b=B[i]-A[i]*x,d=gcd(M[i],a);
        if(b%d!=0) return make_pair(0,-1);
        LL t=b/d*inv(a/d,M[i]/d)%(M[i]/d);
        x=x+m*t;
        m*=M[i]/d;
    }
    x=(x%m+m)%m;
    return make_pair(x,m);
}
int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=0;i<n;i++)
        {
            scanf("%I64d%I64d",&M[i],&B[i]);
            A[i]=1;
        }
        pair<LL,LL> s=linear();
        if(s.second==-1) printf("-1\n");
        else printf("%I64d\n",s.first);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lhhnb/article/details/80279531