joj1175

 1175: The Binomial Function


Result TIME Limit MEMORY Limit Run Times AC Times JUDGE
3s 8192K 2837 844 Standard

1st Jilin University ACM International Collegiate Programming Contest

In this problem, you are to write a program to make the value of the binomial function:

where n and m are integers.

Input Specification

The input consists of several pairs of n and m(0<=n, m<=30). The end of input is marked by n=m=0, which should not be processed.

Output Specification

For each pair of n and m, you should print a line like this: "Binom(n, m) = v", where n, m and v have to be replaced by the values of n, m and v.

Sample Input

5 5

7 0

5 9

0 0

Sample Output

Binom(5, 5) = 1

Binom(7, 0) = 1

Binom(5, 9) = 32

 
 
主要是递归效率的问题,直接写递归会超时。用备忘优化一下AC。改成递推写,AC。
 
 1 #include <stdio.h>
2
3 int array[31][31];
4
5 int binomA(int a, int b); //纯递归,会超时
6 int binomB(int a, int b); //带有备忘录
7 int binomC(int a, int b); //递推写法
8
9 int main(void)
10 {
11 freopen("in.txt", "r", stdin);
12
13 int a, b;
14
15 while ((scanf("%d%d", &a, &b))==2)
16 {
17 if (0==a && 0==b)
18 {
19 break;
20 }
21 printf("Binom(%d, %d) = %d\n", a, b, binomB(a, b));
22 }
23
24
25 return 0;
26 }
27
28 int binomA(int a, int b)
29 {
30 if (0==a || 0==b || a==b)
31 {
32 return 1;
33 }
34 else
35 {
36 return binomA(a-1, b)+binomA(a-1, b-1);
37 }
38 }
39
40 int binomB(int a, int b)
41 {
42 if (0==a || 0==b || a==b)
43 {
44 return 1;
45 }
46 else if (array[a][b])
47 {
48 return array[a][b];
49 }
50 else
51 {
52 return array[a][b] = binomB(a-1,b)+binomB(a-1,b-1);
53 }
54 }
55
56
57 int binomC(int a, int b)
58 {
59 int i, j;
60 for (i=0; i<31; i++)
61 {
62 array[0][i] = 1;
63 array[i][0] = 1;
64 array[i][i] = 1;
65 }
66 for (i=1; i<31; i++)
67 {
68 for (int j=1; j<31; j++)
69 {
70 if (i != j)
71 {
72 array[i][j] = array[i-1][j]+array[i-1][j-1];
73 }
74 }
75 }
76 return array[a][b];
77 }

你可能感兴趣的:(OJ)