Codeforces Round #131 (Div. 2) / 214A System of Equations(枚举&优化)

本博客介绍了一个用于解决特定数学系统方程的高效算法。通过输入两个整数n和m,读者可以了解如何计算满足给定系统的整数对的数量。文中详细解释了算法的实现,并提供了优化后的代码,使得解决方案在时间和空间复杂度上更为高效。

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

A. System of Equations
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?

You are given a system of equations:

You should count, how many there are pairs of integers (a, b) (0 ≤ a, b) which satisfy the system.

Input

A single line contains two integers n, m (1 ≤ n, m ≤ 1000) — the parameters of the system. The numbers on the line are separated by a space.

Output

On a single line print the answer to the problem.

Sample test(s)
input
9 3
output
1
input
14 28
output
1
input
4 20
output
0
Note

In the first sample the suitable pair is integers (3, 0). In the second sample the suitable pair is integers (3, 5). In the third sample there is no suitable pair.


数据范围很小,直接暴力搞定。


完整代码:

/*30ms,0KB*/

#include<cstdio>
#include<cmath>

int main()
{
	int n, m, a, b, count = 0;
	scanf("%d%d", &n, &m);
	int sqrtm = (int)sqrt((double)m);
	for (b = 0; b <= sqrtm; ++b)
	{
		a = m - b * b;
		if (a * a + b == n)
			++count;
	}
	printf("%d", count);
	return 0;
}



优化:

经测试得,只有当m=n=1时才有两解(1,0)和(0,1),其他情况至多有一解。

/*30ms,0KB*/

#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;

int main()
{
	int n, m, a, b;
	scanf("%d%d", &n, &m);
	if (n == m)
	{
		if (n == 1)
			putchar('2');
		else
		{
			double ans = (sqrt((double)4 * n + 1) - 1) / 2;
			putchar(fabs(ans - (int)ans < 1e-9) ? '1' : '0');
		}
	}
	else
	{
		bool has = false;
		if (n < m)
		{
			int minb = min(n, (int)sqrt((double)m));
			for (b = 0; b <= minb; ++b)
			{
				a = m - b * b;
				if (a * a + b == n)
				{
					has = true;
					break;
				}
			}
		}
		else
		{
			int mina = min(m, (int)sqrt((double)n));
			for (a = 0; a <= mina; ++a)
			{
				b = n - a * a;
				if (b * b + a == m)
				{
					has = true;
					break;
				}
			}
		}
		putchar(has ? '1' : '0');
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值