題意:給定三個串,問c串是否能由a,b串任意組合在一起組成,但注意a,b串任意組合需要保證a,b原串的順序 例如ab,cd可組成acbd,但不能組成adcb。
分析:對字符串上的dp還是不敏感啊,雖然挺裸的....dp[i][j] 表示a串前i個,b串前j個字母能組成c串前i+j個字母。所以dp[lena-1][lenb-1] = 1; 就行了。
從後往前找就很好找了,從c串最後一個字符開始遞歸搜索。
#include <cstdio> #include <iostream> #include <cstring> #include <cmath> #include <algorithm> # define MAX 222 using namespace std; char a[MAX],b[MAX],c[MAX*2]; int dp[MAX][MAX]; int lena,lenb,lenc; int dfs(int i,int j,int k) { //cout << i << ' ' << j << ' ' << k << endl; //cout << a[i] << ' ' << b[j] << ' ' << c[k] << endl; if(dp[i][j] != -1 && i >=0 && j >=0) return dp[i][j]; if(k == 0 && (a[i] == c[k] || b[j] == c[k])) return 1; if(i != -1 && a[i] == c[k]) { dp[i][j] = max(dp[i][j],dfs(i-1,j,k-1)); } if(j != -1 && b[j] == c[k]) { dp[i][j] = max(dp[i][j],dfs(i,j-1,k-1)); } if(dp[i][j] == -1) dp[i][j] = 0; return dp[i][j]; } int main() { //freopen("D:\\in.txt","r",stdin); //freopen("D:\\out2.txt","w",stdout); int T; int casee = 1; cin >> T; while(T --) { memset(dp,-1,sizeof(dp)); scanf("%s%s%s",a,b,c); printf("Data set %d: ",casee++); lena = strlen(a); lenb = strlen(b); lenc = strlen(c); //cout << lena << ' ' << lenb << ' ' << lenc << endl; if(lena + lenb != lenc) { puts("no"); continue; } if(dfs(lena-1,lenb-1,lenc-1)) { puts("yes"); } else puts("no"); } return 0; } #include <cstdio> #include <iostream> #include <cstring> #include <cmath> #include <algorithm> # define MAX 222 using namespace std; char a[MAX],b[MAX],c[MAX*2]; int dp[MAX][MAX]; int lena,lenb,lenc; int dfs(int i,int j,int k) { //cout << i << ' ' << j << ' ' << k << endl; //cout << a[i] << ' ' << b[j] << ' ' << c[k] << endl; if(dp[i][j] != -1 && i >=0 && j >=0) return dp[i][j]; if(k == 0 && (a[i] == c[k] || b[j] == c[k])) return 1; if(i != -1 && a[i] == c[k]) { dp[i][j] = max(dp[i][j],dfs(i-1,j,k-1)); } if(j != -1 && b[j] == c[k]) { dp[i][j] = max(dp[i][j],dfs(i,j-1,k-1)); } if(dp[i][j] == -1) dp[i][j] = 0; return dp[i][j]; } int main() { //freopen("D:\\in.txt","r",stdin); //freopen("D:\\out2.txt","w",stdout); int T; int casee = 1; cin >> T; while(T --) { memset(dp,-1,sizeof(dp)); scanf("%s%s%s",a,b,c); printf("Data set %d: ",casee++); lena = strlen(a); lenb = strlen(b); lenc = strlen(c); //cout << lena << ' ' << lenb << ' ' << lenc << endl; if(lena + lenb != lenc) { puts("no"); continue; } if(dfs(lena-1,lenb-1,lenc-1)) { puts("yes"); } else puts("no"); } return 0; }