HDOJ 4790 Just Random, hdoj4790
Http://www.cnblogs.com/xin-hua/p/3553045.html
Idea: For a <= x <= B, c <= y <= d, the matching result is ans = f (B, d)-f (B, C-1) -f (A-1, d) + f (A-1, C-1 ).
Function f (a, B) is the result of calculating 0 <= x <= a, 0 <= y <= B to meet the conditions. This makes computing very convenient.
For example, f (16,7), p = 6, m = 2.
For x: 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4
For y: 0 1 2 3 4 5 0 1
It is easy to know that the number of (0 1 2 3 4 5) pairs in xy is p.
In this way, set A to (0 1 2 3 4 5 5 0 1 2 3 4 5), and set B to (0 1 2 3 4 ).
The C set is (0 1 2 3 4 5), and the D set is (0 1 ).
This can be divided into four parts for calculation.
Just Random
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission (s): 1151 Accepted Submission (s): 315
Problem Description 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.
Input 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 ).
Output 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 shoshould be presented in the simplest form (with the smallest denominator), but always with a denominator (even if it is the unit ).
Sample Input
40 5 0 5 3 00 999999 0 999999 1000000 00 3 0 3 8 73 3 4 4 7 0
Sample Output
Case #1: 1/3Case #2: 1/1000000Case #3: 0/1Case #4: 1/1
Source2013 Asia Chengdu Regional Contest
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;typedef long long int LL;LL a,b,c,d,p,m;LL getF(LL x,LL y){ x++,y++; LL nn=x/p,mm=y/p; LL rn=x%p,rm=y%p; LL res1=nn*mm*p; LL res2=nn*rm; LL res3=mm*rn; LL res4=0; if(rn<=rm) { LL l1=rn; LL l2=rm; for(LL i=m+1;i<rn+rm;i+=p) { if(i<l1) res4+=i; else if(i>=l1&&i<=l2) res4+=rn; else res4+=rn+rm-i; } } else { LL l1=rm; LL l2=rn; for(LL i=m+1;i<rn+rm;i+=p) { if(i<l1) res4+=i; else if(i>=l1&&i<=l2) res4+=rm; else res4+=rn+rm-i; } } return res1+res2+res3+res4;}LL gcd(LL a,LL b){ if(b==0) return a; return gcd(b,a%b);}int main(){int T_T,cas=1;scanf("%d",&T_T);while(T_T--){cin>>a>>b>>c>>d>>p>>m; LL A=(b-a+1)*(d-c+1); LL B=getF(b,d)-getF(a-1,d)-getF(b,c-1)+getF(a-1,c-1); LL G=gcd(A,B); cout<<"Case #"<<cas++<<": "<<B/G<<"/"<<A/G<<endl; } return 0;}