Enter three strings str1, str2, and str3. Determine whether str3 can be composed of str1 and str2.
For example, CAT and tree can form tcraete, so yes is output.
It took me half a day to break my head, think about N implementation methods, and finally find a method that I think is good. Then write the code and submit it immediately. A timeout occurs,
I am confused. The data Scope of this question is very small, and I think my method should be time-saving, so it is a waste of time without repeated computing .......
Finally, I read discuss and finally understood a situation.
Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab
Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac
Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaacaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab
It takes several seconds for my program to run the data.
It depends on people's code, or the old method.
# Include <stdio. h> # include <string. h> int main () {int I, J, K, T; int L1, L2, OK [202] [202]; char str1 [201], str2 [201], str3 [402]; /********************* OK [I] [J] indicates that the first I character of str1 can be and the first J characters of str2 constitute the first I + J characters of str3. False indicates no. * *********************/Scanf ("% d", & T ); for (I = 1; I <= T; I ++) {scanf ("% S % s", str1, str2, str3); memset (OK, 0, sizeof (OK); L1 = strlen (str1); L2 = strlen (str2); OK [0] [0] = 1; for (j = 1; j <= L1; j ++) {If (OK [J-1] [0] = 1 & str1 [J-1] = str3 [J-1]) OK [J] [0] = 1; else break;} For (j = 1; j <= L2; j ++) {If (OK [0] [J-1] = 1 & str2 [J-1] = str3 [J-1]) OK [0] [J] = 1; else break ;} for (j = 1; j <= L1; j ++) {for (k = 1; k <= L2; k ++) {If (OK [J-1] [k] = 1 & str1 [J-1] = str3 [J + k-1] | OK [J] [k-1] = 1 & & str2 [k-1] = str3 [J + k-1]) OK [J] [k] = 1 ;}} if (OK [L1] [L2] = 1) printf ("Data Set % d: yes/N ", i); else printf ("Data Set % d: No/N", I );}}
However, we found that yuyu_myself is actually made by DFS, and the length of time, memory, and code is much longer than that of my code.
This is strange. Isn't dynamic planning the most time-saving? Is it because the data in this question is too small to show the advantage of DP?
#include <stdio.h>#include <string.h>#define N 202char s1[N], s2[N], s[N+N];int dfs(int x, int y){ if (x == -1 && y == -1) return 1; if (x >= 0 && s1[x] == s[x + y + 1]) if (dfs(x - 1, y)) return 1; if (y >= 0 && s2[y] == s[x + y + 1]) if (dfs(x, y - 1)) return 1; return 0;}int main(void){ int n, i; scanf("%d", &n); for (i = 1; i <= n; i++) { scanf("%s %s %s", s1, s2, s); if ( dfs(strlen(s1)-1, strlen(s2)-1) ) printf("Data set %d: yes/n", i); else printf("Data set %d: no/n", i); } return 0;}