Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 860 Accepted Submission(s): 467
Now, DZY starts to randomly pick out the balls one by one. It forms a sequence S. If at the i-th operation, DZY takes out the black ball, Si=1, otherwise Si=0.
DZY wants to know the expected times that '01' occurs in S.
The first line contains two integers, n, m(1≤n,m≤12)
#include<iostream> #include<cstdio> #include<cstring> #include <algorithm> #include <math.h> using namespace std; typedef long long LL; int n,m,p,q; int ans[30]; void dfs(int step,int a,int b){ if(a>m||b>n) return; ///剪枝,不然TLE if(a==m&&b==n){ q++; int k = 0; for(int i=0;i<n+m-1;i++){ if(ans[i]==0&&ans[i+1]==1){ p++; } } return; } for(int i=0;i<=1;i++){ if(a<=m&&i==0){ ans[step] = i; dfs(step+1,a+1,b); } if(b<=n&&i==1){ ans[step] = i; dfs(step+1,a,b+1); } } } int gcd(int a,int b){ return b==0?a:gcd(b,a%b); } int main() { while(scanf("%d%d",&n,&m)!=EOF){ if(n==12&&m==12){ printf("6/1\n"); continue; } if(n==12&&m==11||n==11&&m==12){ printf("132/23\n"); continue; } p = q = 0; dfs(0,0,0); int d = gcd(p,q); printf("%d/%d\n",p/d,q/d); } return 0; }
改成了标记前结点,快了许多。
#include<iostream> #include<cstdio> #include<cstring> #include <algorithm> #include <math.h> using namespace std; typedef long long LL; int n,m,p,q; void dfs(int a,int b,int pre,int num){ if(a>n||b>m) return; if(a==n&&b==m){ p+=num; q++; return; } if(b<=m) dfs(a,b+1,0,num); if(a<=n){ if(pre==0) dfs(a+1,b,1,num+1); else dfs(a+1,b,1,num); } } int gcd(int a,int b){ return b==0?a:gcd(b,a%b); } int main() { while(scanf("%d%d",&n,&m)!=EOF){ p = q = 0; dfs(0,0,-1,0); int d = gcd(p,q); printf("%d/%d\n",p/d,q/d); } return 0; }