题意:
给k个正整数a1....ak,和k个正整数r1....rk,求满足 m mod ai = ri 的最小解m。
解析:
线性同余方程组的求解。不断合并方程。
其中有个证明:(转自 http://www.csdn123.com/itweb.php?url=aHR0cDovL3d3dy5jbmJsb2dzLmNvbS9oZXdlaXlvdTE5OTMvYXJjaGl2ZS8yMDEzLzA5LzA0LzMzMDE4OTQuaHRtbA==)
觉得不错,贴上来:
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#include <climits>
#include <cassert>
#define LL long long
using namespace std;
const int maxn = 1e6;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = 4 * atan(1.0);
const double ee = exp(1.0);
void exgcd(LL a, LL b, LL& d, LL& x, LL& y)
{
if (b == 0)
{
d = a;
x = 1;
y = 0;
}
else
{
exgcd(b, a % b, d, y, x);
y -= x * (a / b);
}
}
LL n;
LL solve()
{
bool flag = true;
LL a1, r1, a2, r2;
LL x, y, d;
scanf("%lld%lld", &a1, &r1);
for (LL i = 1; i < n; i++)
{
scanf("%lld%lld", &a2, &r2);
LL a = a1, b = a2, c = r2 - r1;
exgcd(a, b, d, x, y);
if (c % d)
flag = false;
int r = b / d;
x = c / d * x;
x = (x % r + r) % r;
r1 = a1 * x + r1;
a1 = a2 / d * a1;
}
if (!flag)
r1 = -1;
return r1;
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif // LOCAL
while (scanf("%lld", &n) == 1)
{
printf("%lld\n", solve());
}
return 0;
}
hdu 1573:
求最后解小于N的个数是多少个。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#include <climits>
#include <cassert>
#define LL long long
using namespace std;
const int maxn = 1e6;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = 4 * atan(1.0);
const double ee = exp(1.0);
int N, M;
LL A[10], B[10];
void exgcd(LL a, LL b, LL& d, LL& x, LL& y)
{
if (b == 0)
{
d = a;
x = 1;
y = 0;
}
else
{
exgcd(b, a % b, d, y, x);
y -= (a / b) * x;
}
}
LL solve()
{
LL x, y, d;
LL a1 = A[0], b1 = B[0];
bool have = true;
for (int i = 1; i < M; i++)
{
LL a2 = A[i], b2 = B[i];
LL a = a1, b = a2, c = b2 - b1;
exgcd(a, b, d, x, y);
if (c % d)
{
have = false;
break;
}
LL r = b / d;
x = c / d * x;
x = (x % r + r) % r;
b1 = a1 * x + b1;
a1 = a1 / d * a2;
}
if (!have || b1 > N)
return 0;
if (b1 == 0)///减本身 N - 0 与 N - a1 ...
b1 = a1;
return (N - b1) / a1 + 1;///b1 , b1 + a1, b1 + 2*a1, b2 + 3*a1....
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif // LOCAL
int ncase;
scanf("%d", &ncase);
while (ncase--)
{
scanf("%d%d", &N, &M);
for (int i = 0; i < M; i++)
{
scanf("%I64d", &A[i]);
}
for (int i = 0; i < M; i++)
{
scanf("%I64d", &B[i]);
}
printf("%I64d\n", solve());
}
return 0;
}