您的位置:首页 > 其它

uva1625 颜色的长度

2016-08-05 01:00 176 查看
另一个递推模板,遍历完上一层,然后下一层就可以利用i-1或者j-1.

两个队列的类似最长公共子序列问题常定义状态为,分别移动了多少个元素。

复杂代价预处理,然后状态转换时直接调用。

滚动数组可以利用多层来表示相邻层次关系,利用t^=1 来进行0和1的状态转换。

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=51186

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

const int maxn = 5000 + 5;
const int INF = 1000000000;

char p[maxn], q[maxn]; // starts from position 1
int sp[26], sq[26], ep[26], eq[26]; // sp[i] start positions of character i in p
int d[2][maxn], c[2][maxn]; // c[i][j]: how many "incomplete" colors in the mixed sequence

int main() {
int T;
scanf("%d", &T);
while(T--) {
scanf("%s%s", p+1, q+1);

int n = strlen(p+1);
int m = strlen(q+1);
for(int i = 1; i <= n; i++) p[i] -= 'A';//inti the elements to convenient to express
for(int i = 1; i <= m; i++) q[i] -= 'A';

// calculate s and e
for(int i = 0; i < 26; i++) { sp[i] = sq[i] = INF; ep[i] = eq[i] = 0; }
for(int i = 1; i <= n; i++) {
sp[p[i]] = min(sp[p[i]], i);//need init to INF
ep[p[i]] = i;
}
for(int i = 1; i <= m; i++) {
sq[q[i]] = min(sq[q[i]], i);
eq[q[i]] = i;
}

// dp
int t = 0;
memset(c, 0, sizeof(c));
memset(d, 0, sizeof(d));
for(int i = 0; i <= n; i++){
for(int j = 0; j <= m; j++){
if(!i && !j) continue;

// calculate d
int v1 = INF, v2 = INF;
//use scrollable array, t and t^1 represent the relationship of level
if(i) v1 = d[t^1][j] + c[t^1][j]; // remove from p
if(j) v2 = d[t][j - 1] + c[t][j - 1]; // remove from q
d[t][j] = min(v1, v2);

// calculate c
if(i) {
c[t][j] = c[t^1][j];
//if i is end,--,other wise ++
if(sp[p[i]] == i && sq[p[i]] > j) c[t][j]++;
if(ep[p[i]] == i && eq[p[i]] <= j) c[t][j]--;
} else if(j) {
c[t][j] = c[t][j - 1];
if(sq[q[j]] == j && sp[q[j]] > i) c[t][j]++;
if(eq[q[j]] == j && ep[q[j]] <= i) c[t][j]--;
}
}
t ^= 1;//exchange the state
}
printf("%d\n", d[t^1][m]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uva1625 动态规划