Codeforces Round #657 (Div. 2)——B. Dubious Cyrpto题解

2020/7/20
题目:
Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer n, he encrypts it in the following way: he picks three integers a, b and c such that l≤a,b,c≤r, and then he computes the encrypted value m=n⋅a+b−c.

Unfortunately, an adversary intercepted the values l, r and m. Is it possible to recover the original values of a, b and c from this information? More formally, you are asked to find any values of a, b and c such that

a, b and c are integers,
l≤a,b,c≤r,
there exists a strictly positive integer n, such that n⋅a+b−c=m.
题意:
题意很简单,给你l、r、m,让你找到a,b,c(均在l和r之间),存在一个正整数n使得n*a+b-c=m;

思路:
首先考虑n*a与m的差值,不难发现,对于所有正整数n使得n*a和m的差值最小为m%a和a-m%a(当a>m的时候,则只有a-m%a)。具体见图:
Codeforces Round #657 (Div. 2)——B. Dubious Cyrpto题解_第1张图片
因此,若想使得n*a+b-c=m,则只要|b-c|>=m%a,或者|b-c|<=a-m%a即可。(还是若i>m,则只能|b-c|<=a-m%a),易得|b-c|<=r-l。所以我们只需要枚举a从l到r,看看存不存在上述的情况,然后根据差值赋值即可。
代码:

#include
using namespace std;
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		long long l, r, m;
		cin >> l >> r >> m;
		long long i;
		long long a, b, c;
		for (i = l; i <= r; i++)
		{
			if (m >= i)
			{
				if (m % i<= (r - l))
				{
					a = i;
					c = l;
					b = l + m % i;
					break;
				}
				if (i - m % i <= (r - l))
				{
					a = i;
					b = l;
					c = l + i - m % i;
					break;
				}
			}
			else
			{
				if (i-m <= (r - l))
				{
					a = i;
					b = l;
					c = l + i - m;
					break;
				}
			}
		}
		cout << a << ' ' << b << ' ' << c << endl;
	}
	return 0;
}

你可能感兴趣的:(刷题记录,算法,c++,c语言)