您的位置:首页 > 其它

UVA - 10029 Edit Step Ladders

2015-04-07 19:16 218 查看
记忆化搜索没什么问题,关键是建图,用到了哈希表,开始估计复杂度过高,但还是a了,有可能数据比较弱

#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#define MAX 26000
#define HASHSIZE 500007
using namespace std;

char s[MAX][17];
int words=0,head[HASHSIZE],next[MAX],amount[MAX];
vector<int>edge[MAX];

int hash(char *p){
int len=strlen(p),ret=0;
for(int i=0;i<len;i++)
ret=(ret*26+p[i]-'a')%HASHSIZE;
return ret;
}

void insert(int index){
int hashvalue=hash(s[index]),u=head[hashvalue];
next[index]=u;
head[hashvalue]=index;
}

void query(char *p,int index){
int hashvalue=hash(p),u=head[hashvalue];
while(u!=-1){
if(strcmp(p,s[u])==0){
if(u>index)
edge[u].push_back(index);
}
u=next[u];
}
}

void add(int s_i){
int len=strlen(s[s_i]),index;
char temp[18];
for(int i=0;i<=len;i++){
index=0;
for(int j=0;j<len;j++,index++){
if(j==i){
temp[++index]=s[s_i][j];
}
else{
temp[index]=s[s_i][j];
}
}
temp[len+1]=0;
for(int j=0;j<26;j++){
temp[i]='a'+j;
query(temp,s_i);
}
}
}

void delet(int s_i){
char temp[18];
int index,len=strlen(s[s_i]);
for(int i=0;i<len;i++){
index=0;
for(int j=0;j<len;j++,index++){
if(j==i){
index--;
continue;
}
else
temp[index]=s[s_i][j];
}
temp[len-1]=0;
query(temp,s_i);
}
}

void change(int s_i){
char temp[18];
int len=strlen(s[s_i]);
for(int i=0;i<len;i++){
strcpy(temp,s[s_i]);
for(int j=0;j<26;j++){
if('a'+j==s[s_i][i])
continue;
temp[i]=j+'a';
query(temp,s_i);
}
}
}

void build(){
for(int i=0;i<words;i++){
add(i);
delet(i);
change(i);
}
}

int dfs(int index){
if(amount[index]!=-1)
return amount[index];
amount[index]=0;
int sizet=edge[index].size();
for(int i=0;i<sizet;i++){
amount[index]=max(amount[index],dfs(edge[index][i])+1);
}
return amount[index];
}

int main(){
memset(head,-1,HASHSIZE*4);
memset(amount,-1,MAX*4);
while(cin>>s[words]){
insert(words);
words++;
}
build();
int ans=0;
for(int i=0;i<words;i++){
dfs(i);
ans=max(ans,amount[i]);
}
cout<<ans+1<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: