您的位置:首页 > 其它

【POJ】2891 Strange Way to Express Integers

2016-06-17 22:04 363 查看
1. 题意描述
已知数$X$模$n$个$m_i$的结果分别为$r_i$,求$X$的值。

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

3. 代码

/*  */
#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <deque>
#include <bitset>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <climits>
#include <cctype>
#include <cassert>
#include <functional>
#include <iterator>
#include <iomanip>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,1024000")

#define sti                set<int>
#define stpii            set<pair<int, int> >
#define mpii            map<int,int>
#define vi                vector<int>
#define pii                pair<int,int>
#define vpii            vector<pair<int,int> >
#define rep(i, a, n)     for (int i=a;i<n;++i)
#define per(i, a, n)     for (int i=n-1;i>=a;--i)
#define clr                clear
#define pb                 push_back
#define mp                 make_pair
#define fir                first
#define sec                second
#define all(x)             (x).begin(),(x).end()
#define SZ(x)             ((int)(x).size())
#define lson            l, mid, rt<<1
#define rson            mid+1, r, rt<<1|1

typedef long long LL;
const int maxn = 1e5+5;
LL a[maxn], b[maxn];
int n;
bool flag;

void egcd(LL a, LL b, LL& d, LL& x, LL& y) {
if (!b) {
d = a;
x = 1;
y = 0;
} else {
egcd(b, a%b, d, y, x);
y -= a/b*x;
}
}

LL china(int n, LL *r, LL *m) {
LL M = m[0], R = r[0], x, y, d;

rep(i, 1, n) {
egcd(M, m[i], d, x, y);
if ((r[i] - R) % d)    return -1;
x = (r[i] - R) / d * x % (m[i] / d);
R += x * M;
M = M / d * m[i];
R %= M;
}

return (R + M) % M;
}

void solve() {
LL ans = china(n, b, a);
printf("%I64d\n", ans);
}

int main() {
cin.tie(0);
ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif

while (scanf("%d", &n)!=EOF) {
rep(i, 0, n)
scanf("%I64d%I64d", &a[i],&b[i]);
solve();
}

#ifndef ONLINE_JUDGE
printf("time = %ldms.\n", clock());
#endif

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: