题意:给出一些字符串,从中选出一个的序列,是他相邻的两个字符串的区别是相差一个字符,问这样的序列最长是多少。
题解:用一个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;
}