X问题
Problem Description
求在小于等于N的正整数中有多少个X满足:X mod a[0] = b[0], X mod a[1] = b[1], X mod a[2] = b[2], …, X mod a[i] = b[i], … (0 < a[i] <= 10)。
Input
输入数据的第一行为一个正整数T,表示有T组测试数据。每组测试数据的第一行为两个正整数N,M (0 < N <= 1000,000,000 , 0 < M <= 10),表示X小于等于N,数组a和b中各有M个元素。接下来两行,每行各有M个正整数,分别为a和b中的元素。
Output
对应每一组输入,在独立一行中输出一个正整数,表示满足条件的X的个数。
Sample Input
3
10 3
1 2 3
0 1 2
100 7
3 4 5 6 7 8 9
1 2 3 4 5 6 7
10000 10
1 2 3 4 5 6 7 8 9 10
0 1 2 3 4 5 6 7 8 9
Sample Output
1
0
3
Author
lwg
Source
HDU 2007-1 Programming Contest
题目类型:线性同余方程组
算法分析:首先计算出方程组的最小非负整数解,如果没有解则直接输出0,反之使用tot += (val - x0) / ans计算在val范围内的解数量,其中ans表示lcm (a1, a2, a3, ……an),注意题目要求输出正整数解,所以初始解为0时要排除掉
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
#include <set> #include <bitset> #include <list> #include <map> #include <stack> #include <queue> #include <deque> #include <string> #include <vector> #include <ios> #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <algorithm> #include <utility> #include <complex> #include <numeric> #include <functional> #include <cmath> #include <ctime> #include <climits> #include <cstdarg> #include <cstdio> #include <cstdlib> #include <cstring> #include <cctype> #include <cassert> #define lson rt << 1, l, m #define rson rt << 1 | 1, m + 1, r using namespace std; const int INF = 0x7FFFFFFF; const double EPS = 1e-10; const double PI = 2 * acos (0.0); const int MOD = 7; const int maxn = 10 + 66; long long n, a[maxn], r[maxn]; long long gcd (long long a, long long b) { if (b == 0) return a; return gcd (b, a % b); } long long gcd_ex (long long a, long long b, long long &x, long long &y) { if (b == 0) { x = 1; y = 0; return a; } long long d = gcd_ex (b, a % b, y, x); y = y - a / b * x; return d; } long long mod_equ_set () { long long M = a[0], R = r[0], x, y, d; for (int i = 1; i < n; i++) { d = gcd_ex (M, a[i], x, y); if ((r[i] - R) % d) return -1; x = (r[i] - R) / d * x % (a[i] / d); R += x * M; M = M / d * a[i]; R %= M; } return R > 0 ? R : R + M; } int main() { // ifstream cin ("aaa.txt"); int t; cin >> t; while (t--) { long long val, ans = 1; cin >> val >> n; for (int i = 0; i < n; i++) { cin >> a[i]; ans = ans / gcd (max (ans, a[i]), min (ans, a[i])) * a[i]; } for (int i = 0; i < n; i++) cin >> r[i]; long long x0 = mod_equ_set (), tot = 0; if (x0 == -1) { cout << "0" << endl; continue; } if (x0 <= val) tot = 1 + (val - x0) / ans; if (x0 == 0 && tot) x0--; cout << tot << endl; } return 0; } |
- « 上一篇:hdu1421
- hdu1576:下一篇 »