Boastin' Red Socks

Boastin' Red Socks

 

Time Limit:   1000MS       Memory Limit:   65535KB
Submissions:   33       Accepted:   10

 

Description
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.

 

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

 

解析:

大致题意:有a只红袜子和b只黑袜子吗,随意从中取出两只红袜子的概率是p/q,知道了p和q的值,求a和b的大小

思路:令j=a,num=a+b;

等式一:(j*(j-1))/(num*(num-1))=p/q,有暴力列举j的值从2~50000,相应就能得到num的值

满足输出即可,注意:以下程序中的j和num与等式一的j、num相反

 

# include<iostream>
# include<stdio.h>
# include<string.h>
# include<math.h>
using namespace std;
long long gcd(long long x,long long y)
{
    if(y==0)return x;
    else return gcd(y,x%y);
}
long long solve(int n,long long p,long long q)
{
    return (long long)sqrt((double)(p*n*(n-1))/q)+1;
}

int main()
{
   long long  num,p,q,temp,rp,j;
   int leap;
   while((scanf("%lld %lld",&p,&q))!=EOF)
   {
       if(q==0&&p==0)break;
       leap=0;
       if(p==0)//红袜子不够的情况
        {
            printf("0 2\n");
            continue;
        }
        if(p==q)//全是红袜子的情况
        {
            printf("2 0\n");
            continue;
        }
       rp=gcd(q,p);
       p/=rp;
       q/=rp;
       for(j=2;j<=50000;j++)
       {
           temp=p*j*(j-1);
           if(temp%q==0)//对满足等式一的j进行论证
           {
               num=solve(j,p,q);
               if(num*(num-1)==temp/q&&num<=j)
               {
                   leap=1;
                   break;
               }
           }
       }
     if(leap)
     cout<<num<<" "<<j-num<<endl;
     else printf("impossible\n");
   }
   return 0;
}

 

 

 

posted on 2013-02-03 18:30  即为将军  阅读(268)  评论(0)    收藏  举报

导航