您的位置:首页 > 其它

hdu 4790 Just Random (思路+分类计算+数学)

2015-08-27 18:44 302 查看
[align=left]Problem Description[/align]
  

Coach Pang and Uncle Yang both love numbers. Every morning they play a game with number together. In each game the following will be done:
  1. Coach Pang randomly choose a integer x in [a, b] with equal probability.
  2. Uncle Yang randomly choose a integer y in [c, d] with equal probability.
  3. If (x + y) mod p = m, they will go out and have a nice day together.
  4. Otherwise, they will do homework that day.
  For given a, b, c, d, p and m, Coach Pang wants to know the probability that they will go out.


[align=left]Input[/align]
  

The first line of the input contains an integer T denoting the number of test cases.
  For each test case, there is one line containing six integers a, b, c, d, p and m(0 <= a <= b <= 109, 0 <=c <= d <= 109, 0 <= m < p <= 109).


[align=left]Output[/align]
  

For each test case output a single line "Case #x: y". x is the case number and y is a fraction with numerator and denominator separated by a slash ('/') as the probability that they will go out. The fraction should be presented in the simplest form (with the smallest denominator), but always with a denominator (even if it is the unit).


[align=left]Sample Input[/align]

4
0 5 0 5 3 0
0 999999 0 999999 1000000 0
0 3 0 3 8 7
3 3 4 4 7 0


[align=left]Sample Output[/align]

Case #1: 1/3
Case #2: 1/1000000
Case #3: 0/1
Case #4: 1/1


[align=left]Source[/align]
2013 Asia Chengdu Regional Contest

思路:对于a<=x<=b,c<=y<=d,满足条件的结果为ans=f(b,d)-f(b,c-1)-f(a-1,d)+f(a-1,c-1)。

而函数f(a,b)是计算0<=x<=a,0<=y<=b满足条件的结果。这样计算就很方便了。

例如:求f(16,7),p=6,m=2.

对于x有:0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4

对于y有:0 1 2 3 4 5 0 1

很容易知道对于xy中的(0 1 2 3 4 5)对满足条件的数目为p。

这样取A集合为(0 1 2 3 4 5 0 1 2 3 4 5),B集合为(0 1 2 3 4)。

C集合为(0 1 2 3 4 5),D集合为(0 1)。

这样就可以分成4部分来计算了。

f(16,7)=A和C满足条件的数+A和D满足条件的数+B和C满足条件的数+B和D满足条件的数。

其中前3个很好求的,关键是B和D满足条件的怎么求!

这个要根据m来分情况。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define ll long long
ll a,b,c,d,p,m;
ll gcd(ll x,ll y)
{
return y==0?x:gcd(y,x%y);
}
ll f(ll x,ll y)
{
if(x<0 || y<0)
return 0;
ll mx=x%p;
ll my=y%p;
ll ans=0;
ans=ans+(x/p)*(y/p)*p;//1
ans=ans+(x/p)*(my+1); //2
ans=ans+(y/p)*(mx+1);//3

if(mx>m)//4
{
ans=ans+min(my,m)+1;
ll t=(p+m-mx);
if(t<=my)
ans=ans+my-t+1;
}
else//4
{
ll t=(p+m-mx)%p;
if(t<=my) ans=ans+min(my-t+1,m-t+1);
}
return ans;
}
int main()
{
int t;
int ac=0;
scanf("%d",&t);
while(t--)
{
printf("Case #%d: ",++ac);
scanf("%I64d%I64d%I64d%I64d%I64d%I64d",&a,&b,&c,&d,&p,&m);
ll ans=f(b,d)-f(b,c-1)-f(a-1,d)+f(a-1,c-1);
ll tot=(b-a+1)*(d-c+1);
ll r=gcd(ans,tot);
printf("%I64d/%I64d\n",ans/r,tot/r);
}
return 0;
}


View Code

[align=left]Recommend[/align]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: