uva 1625 color length

本文介绍了一种基于字符串匹配的算法,该算法通过动态规划的方式解决两个字符串间的匹配问题,并计算出匹配所需的最小费用。代码实现中使用了C语言,涉及字符串处理、动态规划等技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

d[i][j] 表示拿了前i个和前j个后,还所需的“最少费用“。

d[m][n] = 0;

d[i][j] = res[i][j] + min(d[ i+1 ][ j ], d[ i ][ j+1 ] );

计算res可以用一维的,因为每次都可以由前一个推算。


代码


#include <stdio.h>
int min(int i, int h) {return i<h?i:h;}
int max(int i, int h) {return i>h?i:h;}
 
const int TNT = 2000000000, Alpha = 26;
char str[5050], strl[5050];
int m, n, res[5050], d[5050][5050];
void G(char *s,int & a) {
	a = 0;
	char ch;
	do ch = getchar(); while(ch < 'A' || ch > 'Z');
	do s[++a] = ch-'A', ch = getchar(); while(ch >= 'A' && ch <= 'Z');
	s[a+1] = '\0';
	ungetc(ch,stdin);
}
int fead[26], fast[26], sead[26], sast[26];
void commando() {
	for(int i = 0; i < Alpha; i++) {
		fead[i] = sead[i] = TNT; fast[i] = sast[i] = -1;
	}
	for(int i = 1; i <= m; i++ ) {
		if(fead[str[i]] == TNT) fead[str[i]] = i;
		fast[str[i]] = i;
	}
	for(int i = 1; i <= n; i++) {
		if(sead[strl[i]] == TNT) sead[strl[i]] = i;
		sast[strl[i]] = i;
	}
}
int main()
{
	int _case ; scanf("%d",&_case);
	while(_case--) 
	{
		G(str, m); G(strl, n);
		commando();
		d[m][n] = 0; res[n] = 0;
		for(int i = m; i >= 0; i--) {
			for(int j = n; j >= 0; j--) {
				if( j < n) {
					char ch = strl[j+1];
					if(fead[ch]<=i || sead[ch]<=j)
					{
						if(fast[ch] <= i && sast[ch] == j+1)
						    res[j] = res[j+1]+1;
						else res[j] = res[j+1];
					}
					else 
					{
						if(fast[ch] > 0 || sast[ch] > j+1)
							res[j] = res[j+1]-1;
						else res[j] = res[j+1];
					}
					d[i][j] = d[i][j+1] + res[j];
					if( i < m) d[i][j] = min( d[i][j], d[i+1][j] + res[j]);
				}
			}
			//for(int t = 0; t <= n; t++) printf("%d ",res[t]); putchar('\n');
			if(i > 0) {
				char c = str[i];
				if(fead[c] < i || sead[c] <= n)
				{
					if(fast[c] == i) res[n]++;
				}
				else if(fast[c] > i) res[n]--;
				d[i-1][n] = d[i][n] + res[n];
			}
		}
		printf("%d\n",d[0][0]);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值