【POJ 2891】Strange Way to Express Integers

博客围绕一道 exCRT 模板题展开,题目描述了一种用不同正整数除非负整数 m 取余数来表示 m 的方式,给出输入输出要求及示例。分析指出这是 exCRT 模板题,具体做法可参考另一篇关于中国剩余定理的博客,还给出了代码部分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目】

传送门

Description

Elina is reading a book written by Rujia Liu, which introduces a strange way to express non-negative integers. The way is described as following:

Choose k different positive integers a1, a2, …, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1, a2, …, ak are properly chosen, m can be determined, then the pairs (ai, ri) can be used to express m.

“It is easy to calculate the pairs from m,” said Elina. “But how can I find m from the pairs?”

Since Elina is new to programming, this problem is too difficult for her. Can you help her?

Input

The input contains multiple test cases. Each test cases consists of some lines.

  • Line 1: Contains the integer k.
  • Lines 2 ~ k + 1: Each contains a pair of integers ai, ri (1 ≤ i ≤ k).

Output

Output the non-negative integer m on a separate line for each test case. If there are multiple possible values, output the smallest one. If there are no possible values, output -1.

Sample Input

2
8 7
11 9

Sample Output

31

Hint

All integers in the input and the output are non-negative and can be represented by 64-bit integral types.


【分析】

这是一道 exCRT 的模板题。

具体的做法就看我的另一篇博客中国剩余定理


【代码】

#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
void exgcd(ll a,ll b,ll &x,ll &y)
{
	if(!b)  {x=1,y=0;return;}
	exgcd(b,a%b,y,x),y-=a/b*x;
}
int main()
{
	int n,i;
	while(~scanf("%d",&n))
	{
		ll m1,a1,m2,a2,x,y;
		scanf("%lld%lld",&m1,&a1);
		bool flag=true;
		for(i=2;i<=n;++i)
		{
			scanf("%lld%lld",&m2,&a2);
			ll Gcd=__gcd(m1,m2),Lcm=m1*m2/Gcd,A=a2-a1;
			if(A%Gcd)  {flag=false;continue;}
			m1/=Gcd,m2/=Gcd,A/=Gcd;
			exgcd(m1,m2,x,y),x=(x*A%m2+m2)%m2;
			a1+=m1*Gcd*x,m1=Lcm;
		}
		printf("%lld\n",flag?a1:-1);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值