10277 Boastin' Red Socks(概率 暴力枚举)

Problem E - Boastin' Red Socks

You have a drawer that is full of two kinds of socks: red and black. You know that there are at least 2 socks, and not more than 50000. However, you do not know how many there actually are, nor do you know how many are red, or how many are black. (Your mother does the laundry!)

You have noticed, though, that when you reach into the drawer each morning and choose two socks to wear (in pitch darkness, so you cannot distinguish red from black), the probability that you pick two red socks is exactly p/q, where 0 < q and 0 <= p <= q.

From this, can you determine how many socks of each colour are in your drawer? There may be multiple solutions - if so, pick the solution with the fewest total number of socks, but still allowing you to wear a couple of same color socks.

Input

Input consists of multiple problems, each on a separate line. Each problem consists of the integers  p  and  q separated by a single space. Note that  p  and  q  will both fit into an unsigned long integer.

Input is terminated by a line consisting of two zeroes.

Output

For each problem, output a single line consisting of the number of red socks and the number of black socks in your drawer, separated by one space. If there is no solution to the problem, print "impossible".

Sample Input

1 2
6 8
12 2499550020
56 789
0 0

Sample Output

3 1
7 1
4 49992
impossible
题意:给定p和q,然后你有n双红袜子,m双黑袜子,取两次(不放回),都是红袜子的概率为p/q。输出n,m

思路:列出式子 n / (n + m) * (n - 1) / ( n + m - 1) = p / q = n * (n - 1) / (n + m) * (n + m - 1); 然后已知袜子总数为50000.这样只要枚举50000以内,i * (i - 1)的数字作为分母。然后分子为i * (i - 1) / q * p 。分子也要是j * ( j - 1)的形式,在去枚举一次j如果符合就输出即可。

代码:

#include <stdio.h>
#include <string.h>
const long long N = 50000;
long long p, q, n, m, i, j;

void solve() {
	for (i = 2; i <= N; i ++) {
		m = i * (i - 1);
		if (m % q) continue;
		n = m / q * p;
		for (j = 2; j * (j - 1) <= n; j ++) {
			if (j * (j - 1) == n) {
				printf("%lld %lld\n", j, i - j);
				return;
			}
		}
	}
	if (i == N + 1)
		printf("impossible\n");
}

int main() {
	while (~scanf("%lld%lld", &p, &q) && p || q) {
		if (p == q) printf("2 0\n");
		else if (p == 0) printf("0 2\n");
		else solve();
	}
	return 0;
}



你可能感兴趣的:(10277 Boastin' Red Socks(概率 暴力枚举))