Give three strings and ask if the third string can be composed of the first two strings ..
Dfs + pruning ..
[Cpp]
# Include <iostream>
# Include <stdio. h>
# Include <string. h>
# Include <algorithm>
Using namespace std;
Const int maxn = 210;
Char sa [maxn], sb [maxn], p [maxn <1];
// Int dp [maxn] [maxn];
Int lena, lenb, lenp;
Bool dfs (int la, int lb, int lp ){
If (la = lena & lb = lenb) return true;
If (la <lena & sa [la] = p [lp]) {
If (dfs (la + 1, lb, lp + 1) return true;
}
If (lb <lenb & sb [lb] = p [lp]) {
If (dfs (la, lb + 1, lp + 1) return true;
}
Return false;
}
Int main (){
Int t;
Scanf ("% d", & t );
For (int cas = 1; cas <= t; cas ++ ){
Scanf ("% s", sa, sb, p );
Lena = strlen (sa );
Lenb = strlen (sb );
Lenp = strlen (p );
Printf ("Data set % d:", cas );
If (lena + lenb! = Lenp | sa [lena-1]! = P [lenp-1] & sb [lenb-1]! = P [lenp-1]) {puts ("no"); continue ;}
Bool OK = dfs (0, 0, 0 );
If (OK) puts ("yes ");
Else puts ("no ");
}
}
Dp memory ..
[Cpp]
# Include <iostream>
# Include <stdio. h>
# Include <string. h>
# Include <algorithm>
Using namespace std;
Const int maxn = 210;
Char sa [maxn], sb [maxn], p [maxn <1];
Int dp [maxn] [maxn];
Int lena, lenb, lenp;
Bool funDP (int I, int j ){
If (dp [I] [j]! =-1) return dp [I] [j];
If (I = 0 & j = 0) return dp [I] [j] = true;
If (I> 0 & sa [I] = p [I + j]) if (funDP (I-1, j) return dp [I] [j] = true;
If (j> 0 & sb [j] = p [I + j]) if (funDP (I, J-1) return dp [I] [j] = true;
Return dp [I] [j] = false;
}
Int main (){
Int t;
Scanf ("% d", & t );
For (int cas = 1; cas <= t; cas ++ ){
Scanf ("% s", sa + 1, sb + 1, p + 1 );
Lena = strlen (sa + 1 );
Lenb = strlen (sb + 1 );
Lenp = strlen (p + 1 );
// Printf ("% d \ n", lena, lenb, lenp );
Printf ("Data set % d:", cas );
If (lena + lenb! = Lenp | sa [lena]! = P [lenp] & sb [lenb]! = P [lenp]) {puts ("no"); continue ;}
Memset (dp,-1, sizeof (dp ));
Bool OK = funDP (lena, lenb );
If (OK) puts ("yes ");
Else puts ("no ");
}
}
Author: qingniaofy