poj 2891 一般模线性方程

Language:
Strange Way to Express Integers
Time Limit: 1000MS Memory Limit: 131072K
Total Submissions: 12520 Accepted: 3968
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.


Sample Input


2
8 7
11 9
Sample Output


31
Hint


All integers in the input and the output are non-negative and can be represented by 64-bit integral types.



#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#define LL long long
using namespace std;
LL r[10005],m[10005];//a[0],m[0]不使用
LL n;
void extendgcd(LL a,LL b,LL &d,LL &x,LL &y)
{
    if(!b)
    {
        d=a;
        x=1;
        y=0;
    }
    else
    {
        extendgcd(b,a%b,d,y,x);
        y-=x*(a/b);
    }
}
LL extendcrt()
{
    LL M=m[1],R=r[1];
    for(int i=2;i<=n;i++)
    {
        LL x,y,d;
        extendgcd(M,m[i],d,x,y);
        if((r[i]-R)%d)//无解
            return -1;
        x=((r[i]-R)/d*x%m[i]+m[i])%m[i];//x的最小正整数解
        R+=x*M;
        M=M/d*m[i];//求(M,m[i])的最小公倍数
        R%=M;
    }
    if(R<0)
        R+=M;
    return R;
}
int main()
{
    while(cin>>n)
    {
        for(int i=1;i<=n;i++)
            cin>>m[i]>>r[i];
        cout<<extendcrt()<<endl;//若有解,返回最小正整数解,否则返回-1
    }
    return 0;
}



一般模线性方程模板




全局变量:
int r[10005],m[10005];//r[0],m[0]不使用
int n//式子的个数
int extendcrt()//返回方程组的最小非负整数解
{
    int M=m[1],R=r[1];
    for(int i=2;i<=n;i++)
    {
        int x,y,d;
        extendgcd(M,m[i],d,x,y);
        if((r[i]-R)%d)//无解
            return -1;
        x=((r[i]-R)/d*x%m[i]+m[i])%m[i];//x的最小正整数解
        R+=x*M;
        M=M/d*m[i];//求(M,m[i])的最小公倍数
        R%=M;
    }
    if(R<0)
        R+=M;
    return R;
}
int main()
{	初始化n,m[],r[];
cout<<extendcrt()<<endl;//若有解,返回最小正整数解,否则返回-1
}


你可能感兴趣的:(模线性方程)