HDOJ-----1573---X問題(擴展歐幾里得)

X問題

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5621    Accepted Submission(s): 1919


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

做了幾道發現擴展歐幾里得的簡單題貌似就是這個套路了- -

要注意的就是判斷,是否滿足a*x+b*y=c中的c是gcd(a, b)的倍數,不滿足則輸出0,最後還要注意一下最小整數解是否大於給定的N,以及是否爲0,題目要求正整數,捨去0即可

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<set> 
#include<queue>
#include<vector>
#include<functional>
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define CL(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long LL;
const int maxn = 1e5+10;
const int MOD = 1e9+7; 
int n[20], m[20];
void ex_gcd(int a, int b, int& d, int& x, int& y){
	if(!b){
		d = a;
		x = 1;
		y = 0;
	}
	else{
		ex_gcd(b, a%b, d, y, x);
		y -= x*(a/b);
	}
}
int main(){
	int T, d, x, y, m1, m2, m3, n1, n2, n3, v, N, M;
	int kcase = 1;
	scanf("%d", &T);
	while(T--){
		scanf("%d%d", &N, &M);
		for(int i = 1; i <= M; i++) scanf("%d", &m[i]);
		for(int i = 1; i <= M; i++) scanf("%d", &n[i]);
		m1 = m[1]; n1 = n[1];
		bool flag = false;
		for(int i = 2; i <= M; i++){
			m2 = m[i]; n2 = n[i];
			ex_gcd(m1, m2, d, x, y);
			LL c, t, k;
			c = n2-n1;
			if(c % d){
				flag = true;
				break;
			}
			c /= d;
			t = m2/d;
			x *= c;
			k = (x%t+t)%t;
			n1 += m1*k; 
			m1 = m1/d*m2;
			n1 = (n1%m1+m1)%m1;
		}
		if(flag || n1 > N) printf("0\n");
		else{
			if(!n1) printf("%d\n", N/m1);
			else printf("%d\n", (N-n1)/m1 + 1);
		}
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章