UVa 12034 - Race (recursive + Yanghui triangle)

Link:

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3185

 

Title:

A and B race horses, and there are three possibilities for the final ranking: tied first; A first and B second; B first and A second.
Enter n (1≤n≤1000), and find the remainder of dividing the number of possibilities for the final position of n-person horse racing by 10056.

 

analyze:

Let the answer be f(n). Assuming that there are i people in the first place, there are C(n,i) possibilities, and then there are f(ni) possibilities, so the answer is ∑C(n,i)f(ni).
The calculation of the number of combinations can be recursive by Yang Hui's triangle.

 

Code:

 1 import java.io.*;
 2 import java.util.*;
 3 
 4 public class Main {
 5     static final int MOD = 10056;
 6     static final int UP = 1000 + 5;
 7     static int f[] = new int[UP], C[][] = new int[UP][UP];
 8     
 9     static void constant() {
10         for(int n = 0; n < UP; n++) {
11             C[n][0] = C[n][n] = 1;
12             for(int m = 1; m < n; m++)
13                 C[n][m] = (C[n-1][m-1] + C[n-1][m]) % MOD;
14         }
15         
16         f[0] = 1;
17         for(int n = 1; n < UP; n++) 
18             for(int i = 1; i <= n; i++)
19                 f[n] = (f[n] + C[n][i] * f[n-i]) % MOD;
20     }
21     
22     public static void main(String args[]) {
23         Scanner cin = new Scanner(new BufferedInputStream(System.in));
24         constant();
25         
26         int T = cin.nextInt();
27         for(int cases = 1; cases <= T; cases++) {
28             int n = cin.nextInt();
29             System.out.printf("Case %d: %d\n", cases, f[n]);
30         }
31         cin.close();
32     }
33 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325104706&siteId=291194637