hdu 1573 X问题 (中国剩余定理)

X问题

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


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
 

Recommend
linle   |   We have carefully selected several similar problems for you:   1788  1452  1060  1299  1211 
 

Statistic |  Submit |  Discuss | Note

题解:中国剩余定理

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define N 103
#define LL long long
using namespace std;
int t,m;
LL n,a[N],r[N];
LL gcd(LL x,LL y)
{
	LL r;
	while (y) {
		r=y; 
		y=x%y;
		x=r;
	}
	return x;
}
void exgcd(LL a,LL b,LL &x,LL &y)
{
	if (!b) {
		x=1; y=0; return;
	}
	exgcd(b,a%b,x,y);
	LL t=y; 
	y=x-(a/b)*y;
	x=t;
}
LL inv(LL a,LL b)
{
	LL x,y; exgcd(a,b,x,y);
	return x;
}
bool merge(LL a1,LL a2,LL n1,LL n2,LL &aa,LL &rr)
{
	LL c=a2-a1; LL d=gcd(n1,n2);
	if (c%d) return 0;
	c/=d; n1/=d; n2/=d;
	LL x=inv(n1,n2);
	x=(x*c)%n2;
	x=x*(n1*d)+a1;
	rr=n1*n2*d;
	aa=(x%rr+rr)%rr;
	return 1;
}
int main()
{
	freopen("a.in","r",stdin);
	freopen("my.out","w",stdout);
	scanf("%d",&t);
	while (t--) {
		scanf("%I64d%d",&n,&m);
		for (int i=1;i<=m;i++) scanf("%I64d",&r[i]);
		for (int i=1;i<=m;i++) scanf("%I64d",&a[i]);
		LL a1,a2,n1,n2,rr,aa;
		a1=a[1]; n1=r[1]; aa=a1; rr=n1;
		bool pd=false;
		for (int i=2;i<=m;i++) {
			a2=a[i]; n2=r[i];
			if (!merge(a1,a2,n1,n2,aa,rr)) {
				pd=true;
				break;
			}
			a1=aa; n1=rr;
		}
		if (aa>n||pd) printf("0\n");
		else {
			if (aa==n) printf("1\n");
			else {
				LL t=(n-aa)/rr;
				if (!aa) t--;
				printf("%I64d\n",t+1);
			}
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值