HDOJ Just Random 4790【2013成都区域赛J题+等差数列优化】

Just Random

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2102    Accepted Submission(s): 592


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 <= 10 9, 0 <=c <= d <= 10 9, 0 <= m < p <= 10 9).
 

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 should be presented in the simplest form (with the smallest denominator), but always with a denominator (even if it is the unit).
 

Sample Input
   
   
   
   
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
 

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

Source
2013 Asia Chengdu Regional Contest
 

Recommend
We have carefully selected several similar problems for you:   5338  5337  5336  5335  5334 
 

终于看懂这题的代码了。。。

斌神代码:点击打开链接

利用等差数列优化。。。等差数列公式:

等差数列前n项和公式
计算第一个符合条件的a1  然后在题中d=p。

注意计算的位置  计算末项时记得算前面的。

#include <stdio.h>
#include <string.h>
#include <algorithm>

using namespace std;

typedef long long LL;

LL gcd(LL a,LL b)
{
	if(b==0)return a;
	return gcd(b,a%b);
}

int main()
{
	int T;
	scanf("%d",&T);
	int xp=1;
	while(T--){
		LL a,b,c,d,p,m;
		scanf("%lld%lld%lld%lld%lld%lld",&a,&b,&c,&d,&p,&m);
		if((a+d)<(b+c)){
			swap(a,c);
			swap(b,d);
		}
		LL ans=0;
		LL t1=(a+c)%p; 
		LL add=(m-t1+p)%p;
		LL cnt1=(a+c+add-m)/p;//计算a+c后面的第一个符合要求的数
		LL t2=(b+c-1)%p;
		LL s=(t2-m+p)%p;//因为要计算前一个数所以要减去s,为了符合等式减去的是p-(m-t2). 
		LL cnt2=(b+c-1-s-m)/p;//计算b+c前面的第一个符合要求的数
		ans+=(cnt2-cnt1+1)*(1+add)+(cnt2-cnt1+1)*(cnt2-cnt1)/2*p;
		t1=(b+c)%p;
		add=(m-t1+p)%p;
		cnt1=(b+c+add-m)/p;
		t2=(a+d)%p;
		s=(t2-m+p)%p;
		cnt2=(a+d-s-m)/p;
		ans+=(cnt2-cnt1+1)*(b-a+1);
		t1=(a+d+1)%p;
		add=(m-t1+p)%p;
		cnt1=(a+d+1+add-m)/p;
		t2=(b+d)%p;
		s=(t2-m+p)%p;
		cnt2=(b+d-s-m)/p;
		ans+=(cnt2-cnt1+1)*(1+s)+(cnt2-cnt1+1)*(cnt2-cnt1)/2*p;
		long long num=(b-a+1)*(d-c+1);
		LL GCD=gcd(ans,num);
		ans/=GCD;
		num/=GCD;
		printf("Case #%d: %lld/%lld\n",xp++,ans,num);
	}
	return 0;
}


你可能感兴趣的:(HDOJ Just Random 4790【2013成都区域赛J题+等差数列优化】)