【POJ 2891】 Strange Way to Express Integers

【题目链接】

            http://poj.org/problem?id=2891

【算法】

           exgcd

【代码】

           

#include <algorithm>  
#include <bitset>  
#include <cctype>  
#include <cerrno>  
#include <clocale>  
#include <cmath>  
#include <complex>  
#include <cstdio>  
#include <cstdlib>  
#include <cstring>  
#include <ctime>  
#include <deque>  
#include <exception>  
#include <fstream>  
#include <functional>  
#include <limits>  
#include <list>  
#include <map>  
#include <iomanip>  
#include <ios>  
#include <iosfwd>  
#include <iostream>  
#include <istream>  
#include <ostream>  
#include <queue>  
#include <set>  
#include <sstream>  
#include <stdexcept>  
#include <streambuf>  
#include <string>  
#include <utility>  
#include <vector>  
#include <cwchar>  
#include <cwctype>  
#include <stack>  
#include <limits.h>
using namespace std;
typedef long long ll;

int i,k;
ll a[100010],m[100010];
 
inline ll exgcd(ll a,ll b,ll &x,ll &y)
{
        ll g;
        if (b == 0)
        {
                x = 1;
                y = 0;
                return a;
        } else
        {
                g = exgcd(b,a%b,y,x);
                y -= a / b * x;
                return g;
        }
}
inline ll solve()
{
        int i;
        ll g,x,y,M = a[1],R = m[1];
        for (i = 2; i <= k; i++)
        {
                g = exgcd(M,a[i],x,y);
                if ((R - m[i]) % g != 0) return -1;
                x = (R - m[i]) / g * x % a[i];
                R -= x * M;
                M = M / g * a[i];
                R %= M;
        }
        return (R % M + M) % M;
}
int main() 
{
        
        while (scanf("%d",&k) != EOF)
        {
                for (i = 1; i <= k; i++) scanf("%lld%lld",&a[i],&m[i]);
                printf("%lld\n",solve());
        }
        return 0;
    
}

猜你喜欢

转载自www.cnblogs.com/evenbao/p/9285469.html