【UVA-12034】解题报告(递推,DP)

原始题目

12034 - Race

  • Time limit: 1.000 seconds

Disky and Sooma, two of the biggest mega minds of Bangladesh went to a far country. They ate, coded and wandered around, even in their holidays. They passed several months in this way. But everything has an end. A holy person, Munsiji came into their life. Munsiji took them to derby (horse racing). Munsiji enjoyed the race, but as usual Disky and Sooma did their as usual task instead of passing some romantic moments. They were thinking- in how many ways a race can finish! Who knows, maybe this is their romance!

In a race there are n horses. You have to output the number of ways the race can finish. Note that, more than one horse may get the same position. For example, 2 horses can finish in 3 ways. 1. Both first 2. horse1 first and horse2 second 3. horse2 first and horse1 second

Input

Input starts with an integer T (≤ 1000), denoting the number of test cases. Each case starts with a line containing an integer n (1 ≤ n ≤ 1000).

Output

For each case, print the case number and the number of ways the race can finish. The result can be very large, print the result modulo 10056.

Sample Input

3
1
2
3

Sample Output

Case 1: 1
Case 2: 3
Case 3: 13

题目大意

一场赛马比赛中由n匹马,任意两匹马可以同时到达或者一先一后到达,问一共有多少种到达的可能。

解题思路

  • 考虑dp。
  • \(dp[i][j]\)表示i匹马用j次到达的可能情况数。
    • 考虑第i匹马的情况,可能和前i-1匹马一同到达,或者单独到达(即第i匹马到达时有并列,无并列)。\(dp[i][j]=j\*(dp[i-1][j]+dp[i-1][j-1])\),乘j是因为第i匹马名次有j种可能。

解题代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <cstdio>
#include <cstring>
#include <iostream>
#include <set>
#include <algorithm>
#include <queue>
#include <map>
#include <string>
#define eps 1e-8
#define INF 0x3f3f3f3f
#define rep(i,a,n) for(int i=a;i<n;i++)
#define per(i,a,n) for(int i=n-1;i>=a;i--)
using namespace std;
const int maxn=1e8+2;
const int mod=10056;
typedef long long ll;
ll dp[1005][1005];
ll ans[1005];


int main(){
int t;
memset(dp,0,sizeof(dp));
memset(ans,0,sizeof(ans));
dp[1][1]=1;
ans[1]=1;
for(int i=2;i<=1000;i++){
int sum=0;
for(int j=1;j<=i;j++){
if(j==1) dp[i][j]=1;
else dp[i][j]=j*(dp[i-1][j]+dp[i-1][j-1])%mod;
sum=(sum+dp[i][j])%mod;
// cout<<"ans["<<i<<"]="<<ans[i]<<endl;

}
ans[i]=sum;
// cout<<i<<" "<<ans[i]<< " "<<ans[i-1]<<endl;
}
// for(int i=2;i<=1005;i++){
// cout<<"i="<<i<<" "<<ans[i]<<endl;
// }
cin>>t;
int n,cas=1;
while(t--)
{
cin>>n;
cout<<"Case "<<cas++<<": " <<ans[n]<<endl;
}
}

收获与反思

注意取模的运算规则,考虑dp与最终答案的关系。