uva 10029(dp)

题意:给出一些字符串,从中选出一个的序列,是他相邻的两个字符串的区别是相差一个字符,问这样的序列最长是多少。

题解:用一个f[i]数组存前i个字符中存在的最长子序列的长度,每输入一个字符串,就将字符串增删改操作然后和之前的字符串对比,如果存在一个相等的字符串str[i]就得到其f[i],选出最大的赋给当前输入的字符串的f[n]中。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <queue>
using namespace std;
const int N = 20;
const int M = 25005;
char str[M][N];
int n, f[M];

void change(char* a, int pos, char c) {
	a[pos] = c;
	return;
}

void add(char* a, int pos, char c, int len) {
	for (int i = len; i >= pos; i--)
		a[i + 1] = a[i];
	a[pos] = c;
	return;
}

void dec(char* a, int pos, int len) {
	for (int i = pos; i < len; i++)
		a[i] = a[i + 1];
	return;
}

int binary(char* s, int l, int r) {
	while (l <= r) {
		int mid = (l + r) / 2;
		if (strcmp(s, str[mid]) > 0)
			l = mid + 1;
		else if (strcmp(s, str[mid]) == 0)
			return mid;
		else
			r = mid - 1;
	}
	return -1;
}

int main() {
	int res = -1;
	n = 1;
	char s[20];
	while (scanf("%s", str[n]) != EOF) {
		int temp = 1;
		int len = strlen(str[n]);
		for (int i = 0; i < len; i++) {
			strcpy(s, str[n]);
			dec(s, i, len);
			int pos = binary(s, 0, n - 1);
			if (pos != -1 && f[pos] + 1 > temp)
				temp = f[pos] + 1;
			for (int j = 'a'; j <= 'z'; j++) {
				strcpy(s, str[n]);
				add(s, i, j, len);
				int pos = binary(s, 0, n - 1);
				if (pos != -1 && f[pos] + 1 > temp)
					temp = f[pos] + 1;
				strcpy(s, str[n]);
				change(s, i, j);
				pos = binary(s, 0, n - 1);
				if (pos != -1 && f[pos] + 1 > temp)
					temp = f[pos] + 1;
			}
		}
		f[n] = temp;
		if (temp > res)
			res = temp;
		n++;
	}
	printf("%d\n", res);
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值