【POJ】2891 Strange Way to Express Integers

1. 题意描述
已知数$X$模$n$个$m_i$的结果分别为$r_i$,求$X$的值。

2. 基本思路
因为$m_i$并不一定互质,所以此题不能直接用CRT解,不过解法基本是类似的。模板题,解一般模线型方程组。

3. 代码

  1 /*  */
  2 #include <iostream>
  3 #include <sstream>
  4 #include <string>
  5 #include <map>
  6 #include <queue>
  7 #include <set>
  8 #include <stack>
  9 #include <vector>
 10 #include <deque>
 11 #include <bitset>
 12 #include <algorithm>
 13 #include <cstdio>
 14 #include <cmath>
 15 #include <ctime>
 16 #include <cstring>
 17 #include <climits>
 18 #include <cctype>
 19 #include <cassert>
 20 #include <functional>
 21 #include <iterator>
 22 #include <iomanip>
 23 using namespace std;
 24 //#pragma comment(linker,"/STACK:102400000,1024000")
 25 
 26 #define sti                set<int>
 27 #define stpii            set<pair<int, int> >
 28 #define mpii            map<int,int>
 29 #define vi                vector<int>
 30 #define pii                pair<int,int>
 31 #define vpii            vector<pair<int,int> >
 32 #define rep(i, a, n)     for (int i=a;i<n;++i)
 33 #define per(i, a, n)     for (int i=n-1;i>=a;--i)
 34 #define clr                clear
 35 #define pb                 push_back
 36 #define mp                 make_pair
 37 #define fir                first
 38 #define sec                second
 39 #define all(x)             (x).begin(),(x).end()
 40 #define SZ(x)             ((int)(x).size())
 41 #define lson            l, mid, rt<<1
 42 #define rson            mid+1, r, rt<<1|1
 43 
 44 typedef long long LL;
 45 const int maxn = 1e5+5;
 46 LL a[maxn], b[maxn];
 47 int n;
 48 bool flag;
 49 
 50 void egcd(LL a, LL b, LL& d, LL& x, LL& y) {
 51     if (!b) {
 52         d = a;
 53         x = 1;
 54         y = 0;
 55     } else {
 56         egcd(b, a%b, d, y, x);
 57         y -= a/b*x;
 58     }
 59 }
 60 
 61 LL china(int n, LL *r, LL *m) {
 62     LL M = m[0], R = r[0], x, y, d;
 63 
 64     rep(i, 1, n) {
 65         egcd(M, m[i], d, x, y);
 66         if ((r[i] - R) % d)    return -1;
 67         x = (r[i] - R) / d * x % (m[i] / d);
 68         R += x * M;
 69         M = M / d * m[i];
 70         R %= M;
 71     }
 72     
 73     return (R + M) % M;
 74 }
 75 
 76 void solve() {
 77     LL ans = china(n, b, a);
 78     printf("%I64d\n", ans);
 79 }
 80 
 81 int main() {
 82     cin.tie(0);
 83     ios::sync_with_stdio(false);
 84     #ifndef ONLINE_JUDGE
 85         freopen("data.in", "r", stdin);
 86         freopen("data.out", "w", stdout);
 87     #endif
 88     
 89     while (scanf("%d", &n)!=EOF) {
 90         rep(i, 0, n)
 91             scanf("%I64d%I64d", &a[i],&b[i]);
 92         solve();
 93     }
 94     
 95     #ifndef ONLINE_JUDGE
 96         printf("time = %ldms.\n", clock());
 97     #endif
 98     
 99     return 0;
100 }

 

posted on 2016-06-17 22:04  Bombe  阅读(199)  评论(0编辑  收藏  举报

导航