https://www.facebook.com/hackercup/problem/688426044611322/
Solution:
This could be solved by using dynamic programming.
Let's define dp[ i, j ] as the number of ways to reach the final score of i-j.
For the stress-free victory:
The base cases:
dp[ i, 0 ] = 1, 1 <= i <= N
dp[ 0, i ] = 0, 1 <= i <= N
The recurrence:
dp[ i, j ] = 0, if i <= j
dp[ i, j ] = dp[ i-1, j ] + dp[ i, j-1 ], if i > j
The base cases:
dp[ i, 0 ] = 1, 1 <= i <= N
dp[ 0, i ] = 1, 1 <= i <= N
The recurrence:
dp[ i, j ] = dp[ j, j ], if i > j
dp[ i, j ] = dp[ i-1, j ], if i = j
dp[ i, j ] = dp[ i-1, j ] + dp[ i, j-1 ], if i < j
Example codes:
int T = inp.NextInt ( );
long mod = 1000000000 + 7;
long[,] dpstressfree = new long[2001, 2001];
long[,] dpstressfull = new long[2001, 2001];
dpstressfree[0, 0] = 0;
for ( int i = 1; i < 2001; i++ )
{
dpstressfree[i, 0] = 1;
dpstressfree[0, i] = 0;
}
for ( int i = 1; i < 2001; i++ )
{
for ( int j = 1; j < 2001; j++ )
{
if ( i <= j )
dpstressfree[i, j] = 0;
else
{
dpstressfree[i, j] = ( dpstressfree[i - 1, j] + dpstressfree[i, j - 1] ) % mod;
}
}
}
dpstressfull[0, 0] = 1;
for ( int i = 1; i < 2001; i++ )
{
dpstressfull[i, 0] = 1;
dpstressfull[0, i] = 1;
}
for ( int i = 1; i < 2001; i++ )
{
for ( int j = 1; j < 2001; j++ )
{
if ( i > j )
dpstressfull[i, j] = dpstressfull[j, j];
else if ( i == j )
dpstressfull[i, j] = dpstressfull[i - 1, j];
else
{
dpstressfull[i, j] = ( dpstressfull[i - 1, j] + dpstressfull[i, j - 1] ) % mod;
}
}
}
for ( int t = 0; t < T; t++ )
{
string[] s = inp.NextString ( ).Split ( '-' );
int A = int.Parse ( s[0] );
int B = int.Parse ( s[1] );
long ans1=dpstressfree[A, B];
long ans2=dpstressfull[A, B];
Console.WriteLine ( "Case #{0}: {1} {2}", t + 1, ans1, ans2 );
}
No comments:
Post a Comment