首页 > 其他 > 详细

poj——2891 Strange Way to Express Integers

时间:2017-08-12 23:34:50      阅读:193      评论:0      收藏:0      [点我收藏+]
                      Strange Way to Express Integers
Time Limit: 1000MS   Memory Limit: 131072K
Total Submissions: 16839   Accepted: 5625

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 a1a2…, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1a2, …, ak are properly chosen, m can be determined, then the pairs (airi) 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 airi (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.

Source

 
今天最后一个中国剩余定理、、、、、、(还是水体。。。。。)

题目大意: 有一个数mod ri 等于ai  ,求这个数,若求不出来输出“-1”。

代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define N 1000
#define ll long long
using namespace std;
ll n,a[N],m[N];
ll read()
{
    ll x=0,f=1; char ch=getchar();
    while(ch<0||ch>9){if(ch==-)f=-1; ch=getchar();}
    while(ch>=0&&ch<=9){x=x*10+ch-0; ch=getchar();}
    return x*f;
}
ll exgcd(ll a,ll b,ll &x,ll &y)
{
    if(b==0)
    {
        x=1,y=0;
        return a;
    }
    ll r=exgcd(b,a%b,x,y),tmp;
    tmp=x,x=y,y=tmp-a/b*y;
    return r;
}
ll crt()
{
    ll a1=a[1],m1=m[1],a2,m2,c,d;
    for(ll i=2;i<=n;i++)
    {
        m2=m[i],a2=a[i];
        c=a2-a1;ll x=0,y=0;
        d=exgcd(m1,m2,x,y);
        if(c%d) return -1;
        x=x*c/d;
        int mod=m2/d;
        x=(mod+x%mod)%mod;
        a1+=x*m1;m1*=mod;
    }
    if(a1==0) a1+=m1;
    return a1;
}
int main()
{
    while(~scanf("%lld",&n))
    {
        for(ll i=1;i<=n;i++)
         m[i]=read(),a[i]=read();
        printf("%lld\n",crt());
    }
    return 0;
}

 

poj——2891 Strange Way to Express Integers

原文:http://www.cnblogs.com/z360/p/7351742.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!