题意:给定两个序列,让你组成一个新的序列,让两个相同字符的位置最大差之和最小。组成方式只能从一个序列前部拿出一个字符放到新序列中。
析:这个题状态表示和转移很容易想到,主要是在处理上面,dp[i][j] 表示从第一序列中拿了 i 个字符,从第二序列中拿了 j 个字符的最小和是多少,这个要提前预处理每个字符开始出现和最后出现的位置,然后再用一个c数组来记录已经有多少个字符出现,但没有结束。注意要清空。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <sstream> #include <list> #define debug() puts("++++"); #define gcd(a, b) __gcd(a, b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 5000 + 10; const int maxm = maxn * 100; const int mod = 10; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c) { return r >= 0 && r < n && c >= 0 && c < m; } int dp[maxn][maxn], c[maxn][maxn]; int f1[30], f2[30], r1[30], r2[30]; char s1[maxn], s2[maxn]; int a[maxn], b[maxn]; int main(){ int T; cin >> T; while(T--){ scanf("%s", s1); scanf("%s", s2); n = strlen(s1); m = strlen(s2); memset(f1, INF, sizeof f1); memset(f2, INF, sizeof f2); memset(r1, 0, sizeof r1); //must clear memset(r2, 0, sizeof r2); //must clear for(int i = 1; i <= n; ++i){ a[i] = s1[i-1] - 'A'; f1[a[i]] = min(f1[a[i]], i); r1[a[i]] = i; } for(int i = 1; i <= m; ++i){ b[i] = s2[i-1] - 'A'; f2[b[i]] = min(f2[b[i]], i); r2[b[i]] = i; } for(int i = 0; i <= n; ++i) for(int j = 0; j <= m; ++j){ if(!i && !j) continue; int v1 = INF, v2 = INF; if(i) v1 = dp[i-1][j] + c[i-1][j]; if(j) v2 = dp[i][j-1] + c[i][j-1]; dp[i][j] = min(v1, v2); if(j){ c[i][j] = c[i][j-1]; if(f2[b[j]] == j && f1[b[j]] > i) ++c[i][j]; // take care of this '>' not '>=' if(r2[b[j]] == j && r1[b[j]] <= i) --c[i][j]; //take care, too } else{ c[i][j] = c[i-1][j]; if(f1[a[i]] == i && f2[a[i]] > j) ++c[i][j]; if(r1[a[i]] == i && r2[a[i]] <= j) --c[i][j]; } } printf("%d\n", dp[n][m]); } return 0; }