码迷,mamicode.com
首页 > 其他好文 > 详细

poj——2891 Strange Way to Express Integers

时间:2017-08-13 00:06:24      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:des   ios   ide   properly   pre   output   limit   amp   input   

                      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

标签:des   ios   ide   properly   pre   output   limit   amp   input   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!