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

A. System of Equations
http://codeforces.com/problemset/problem/214/A
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;
}

你可能感兴趣的:(ACM,codeforces)