Sgu_214
This topic is similar to the longest common subsequence DP process. You can use F [I] [J] to indicate the optimal solution when λ matches I and μ matches J. Then f [I] [J] will only be obtained in three cases: one case is that λ [I] matches a character (obviously it should match the character with the smallest value added after matching ), one case is that μ [J] matches a character (it should also match the character with the smallest value added after matching ), another case is that λ [I] matches μ [J.
# Include <stdio. h>
# Include < String . H>
# Define Maxd 2010
# Define INF 0x7fffffff
Char A [maxd], B [maxd], Alph [ 300 ];
Long Long Int F [maxd] [maxd];
Int N, Na, Nb, Mina [maxd], minb [maxd], G [maxd] [maxd], p [maxd] [maxd];
Int C [ 600 ], * Ch, ANSA [ 2 * Maxd], Pa, ansb [ 2 * Maxd], PB;
Void Init ()
{
Int I, J, K;
Ch = & C [ 300 ];
N = strlen (Alph + 1 );
Gets (a + 1 );
NA = strlen (a + 1 );
Gets (B + 1 );
NB = strlen (B + 1 );
For (I = 1 ; I <= N; I ++)
Ch [Alph [I] = I;
For (I = 1 ; I <= N; I ++)
{
K = inf;
For (J = 1 ; J <= N; j ++)
{
Scanf ( " % D " , & G [I] [J]);
If (G [I] [J] <= K)
K = G [I] [J], Mina [I] = J;
}
}
For (J = 1 ; J <= N; j ++)
{
K = inf;
For (I = 1 ; I <= N; I ++)
If (G [I] [J] <= K)
K = G [I] [J], minb [J] = I;
}
}
Void DFS ( Int Na, Int NB)
{
If (NA = 0 & Nb =0 )
Return ;
If (P [Na] [Nb] = 0 )
{
ANSA [PA ++] = CH [A [Na], ansb [Pb ++] = CH [B [Nb];
DFS (Na- 1 , Nb- 1 );
}
Else If (P [Na] [Nb]> 0 )
{
ANSA [PA ++] = CH [A [Na], ansb [Pb ++] = P [Na] [Nb];
DFS (Na- 1 , Nb );
}
Else
{
ANSA [PA ++] =-P [Na] [Nb], ansb [Pb ++] = CH [B [Nb];
DFS (Na, Nb- 1 );
}
}
Void Printresult ()
{
Int I, J, K;
Pa = Pb = 0 ;
DFS (Na, Nb );
Printf ( " % I64d \ n " , F [Na] [Nb]);
While (PA)
Printf ( " % C " , Alph [ANSA [-- PA]);
Printf ( " \ N " );
While (PB)
Printf (" % C " , Alph [ansb [-- Pb]);
Printf ( " \ N " );
}
Void Solve ()
{
Int I, J, K, X, Y;
Long Long Int T;
F [ 0 ] [0 ] = 0 ;
T = 0 ;
For (I = 1 ; I <= Na; I ++)
{
X = CH [A [I];
F [I] [ 0 ] = F [I- 1 ] [ 0 ] + G [x] [Mina [X], p [I] [ 0 ] = Mina [x];
}
T =0 ;
For (I = 1 ; I <= Nb; I ++)
{
Y = CH [B [I];
F [ 0 ] [I] = f [ 0 ] [I- 1 ] + G [minb [y] [Y], p [ 0 ] [I] =-minb [y];
}
For (I = 1 ; I <= Na; I ++)
For (J = 1 ; J <= Nb; j ++)
{
X = CH [A [I], y = CH [B [J];
F [I] [J] = f [I- 1 ] [J- 1 ] + G [x] [Y], p [I] [J] = 0 ;
If (F [I- 1 ] [J] + G [x] [Mina [x] <F [I] [J])
F [I] [J] = f [I- 1 ] [J] + G [x] [Mina [X], p [I] [J] = Mina [x];
If (F [I] [J-1 ] + G [minb [y] [Y] <F [I] [J])
F [I] [J] = f [I] [J- 1 ] + G [minb [y] [Y], p [I] [J] =-minb [y];
}
Printresult ();
}
Int Main ()
{
Gets (Alph + 1 );
Init ();
Solve ();
Return 0 ;
}