题意:
给一个字典,里面有好多单词。单词可以由增加、删除、变换,变成另一个单词,问能变换的最长单词长度。
解析:
HASH+dp
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#include <climits>
#include <cassert>
#define LL long long
using namespace std;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = 4 * atan(1.0);
const double ee = exp(1.0);
const int maxn = 25000 + 10;
const int HASH = 1000003;
int n;
int head[HASH], next[maxn];
char s[maxn][20], t[20];
int dp[maxn];
//hash ...
int Hash(char str[])
{
int v = 0, seed = 88;
while (*str)
v = v * seed + *(str++);
return (v & 0x7fffffff) % HASH;
}
void Insert(int x)
{
int h = Hash(s[x]);
next[x] = head[h];
head[h] = x;
}
int Search()
{
int i;
int h = Hash(t);//
for (i = head[h]; i != -1; i = next[i])
{
if (strcmp(t, s[i]) == 0)
{
break;
}
}
return i;
}
//dp ...
void add(char str[], int pos, int key)
{
memset(t, 0, sizeof(t));
int i, j;
for (i = 0, j = 0; i < pos; i++, j++)
{
t[j] = str[i];
}
t[j++] = 'a' + key;
for (; str[i]; i++, j++)
{
t[j] = str[i];
}
t[j] = '\0';
}
void del(char str[], int pos)
{
memset(t, 0, sizeof(t));
int i, j;
for (i = 0, j = 0; i < pos; i++, j++)
{
t[j] = str[i];
}
i++;
for (; str[i]; i++, j++)
{
t[j] = str[i];
}
t[j] = '\0';
}
void change(char str[], int pos, int key)
{
memset(t, 0, sizeof(t));
strcpy(t, str);
t[pos] = 'a' + key;
}
int Dfs(int cur)
{
if (dp[cur] != -1)
return dp[cur];
int res = 0;
int len = strlen(s[cur]);
//add
for (int i = 0; i <= len; i++)
{
for (int k = 0; k < 26; k++)
{
add(s[cur], i, k);
int pos = Search();
if (pos != -1 && strcmp(s[cur], t) < 0)
{
int t = Dfs(pos) + 1;///pos
if (res < t)
{
res = t;
}
}
}
}
//delete
for (int i = 0; i < len; i++)
{
del(s[cur], i);
int pos = Search();
if (pos != -1 && strcmp(s[cur], t) < 0)
{
int t = Dfs(pos) + 1;///pos
if (res < t)
{
res = t;
}
}
}
//change
for (int i = 0; i < len; i++)
{
for (int k = 0; k < 26; k++)
{
change(s[cur], i, k);
int pos = Search();
if (pos != -1 && strcmp(s[cur], t) < 0)
{
int t = Dfs(pos) + 1;///pos
if (res < t)
{
res = t;
}
}
}
}
return dp[cur] = res;
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif // LOCAL
n = 0;
memset(head, -1, sizeof(head));
while (scanf("%s", s[n]) != EOF)
{
Insert(n);
n++;
}
memset(dp, -1, sizeof(dp));
int ans = 0;
for (int i = 0; i < n; i++)
{
int t = Dfs(i) + 1;
if (ans < t)
{
ans = t;
}
}
printf("%d\n", ans);
return 0;
}