解题报告 之 POJ2891 Strange Way to Express Integers

20 篇文章 2 订阅

解题报告 之 POJ2891 Strange Way to Express Integers


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 a1a2…, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainderri. If a1a2, …, ak are properly chosen, m can be determined, then the pairs (airi) 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 airi (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

题目大意:现在将数表示成一种新的形式,即用一个数去除多个数mk,分别得到余数rk,用这些(除数,余数)对来唯一确定本来的数字。有了数num和m1~mn很容易表示成这种形式,但是现在反过来,给你n个(mk,rk)对,让你确定这个数num是多少?不存在输出-1.


分析:裸的解线性同余方程组,说实话我看书没看懂这个代码的原理,特别是要用m2/gcd那里,所以先把代码当接口来用吧。有一个讲解的比较好的博文大家可以看看原理(http://blog.csdn.net/orpinex/article/details/6972654),但是我同样看不懂,等学了中国剩余再返回来看看吧。那么这道题等价于解方程:

≡ r1(mod m1)

≡ r2(mod m2)

……

≡ rn(mod mn)

是线性同余方程组,用模版过吧,虽然原理还不懂。。。Orz。。如果有好心的大神愿意给我讲讲麻烦加我QQ吧 452884244,叩谢。


上代码:

#include<iostream>
#include<algorithm>
using namespace std;

typedef long long ll;

ll exgcd( ll a, ll b, ll& x, ll& y )  //扩展gcd
{
	if(b == 0)
	{
		x = 1;
		y = 0;
		return a;
	}
	ll gcd = exgcd( b, a%b, x, y );
	ll tem = x;
	x = y;
	y = tem - a / b*y;
	return gcd;
}

int main()
{
	int n;
	ll r1, m1, r2, m2, x0, y0;
	while(cin >> n)
	{
		bool flag=1;
		cin >> m1 >> r1;  //以第一个同余方程作为基础
		for(int i = 1; i < n; i++)
		{
			cin >> m2 >> r2;    //处理剩下的同余方程
			ll a = m1, b = m2, c = r2 - r1;
			ll d=exgcd( a, b, x0, y0 );   //求基础解X0和d=GCD

			if(c%d != 0) flag = false;  //无解条件

			ll t = b / d;                                        //看不懂,似乎是在更新一些系数。
			x0 = (x0*(c / d) % t + t) % t;			//看不懂,似乎是在更新一些系数。
			r1 = m1*x0 + r1;								//看不懂,似乎是在更新一些系数。
			m1 = m1*(m2 / d);							//看不懂,似乎是在更新一些系数。
		}
		if(!flag)
		{
			cout << -1 << endl;
			continue;
		}
		cout << r1 << endl;
	}
	return 0;
}

数论难起来真是理解无力。。。。


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值