Hdu 3579 Hello Kiki

大意不再赘述。

思路:

一元同余方程组的解,可以通过两两合并来求解,注意当最后的结果时需要特判,该结果为A数组的最小公倍数,其余的合并求解即可。

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;

typedef long long LL;

int n;
int times;

const int MAXN = 1010;
LL A[MAXN], r[MAXN];

LL lcm;

LL gcd(LL a, LL b)
{
	return b == 0? a : gcd(b, a%b);
}

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

void read_case()
{
	scanf("%d", &n);
	lcm = 1;
	for(int i = 1; i <= n; i++)
	{
		scanf("%lld", &A[i]);
		lcm = lcm / gcd(lcm, A[i]) * A[i];
	}
	for(int i = 1; i <= n; i++) scanf("%lld", &r[i]);
}

void solve()
{
	read_case();
	printf("Case %d: ", ++times);
	LL a, b, c, d, x, y;
	for(int i = 2; i <= n; i++)
	{
		a = A[1], b = A[i], c = r[i]-r[1];
		ex_gcd(a, b, d, x, y);
		if(c % d) { printf("-1\n"); return ;}
		LL b1 = b / d;
		x *= c / d;
		x = (x%b1 + b1) % b1;
		r[1] = A[1]*x + r[1];
		A[1] = A[1]*(A[i] / d);
	}
	if(r[1] == 0) printf("%lld\n", lcm);
	else printf("%lld\n", r[1]);
}

int main()
{
	int T;
	times = 0;
	scanf("%d", &T);
	while(T--)
	{
		solve();
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值