10029 - Edit Step Ladders

描述:字符串有点大,直接用动规的话25000^2肯定会超时,所以需要动规+二分/哈希,我的代码是采用二分,这样的话,不超过2s就可以过了
#include <cstdio>
#include <cstdlib>
#include <cstring>
char str[25010][18];
int v[25010];
int n,sum;
void dic(int x,char *p)
{
    int first=x+1,last=n-1,t;
    while(first<=last)
    {
        t=(first+last)/2;
        if(strcmp(p,str[t])<0) last=t-1;
        else if(strcmp(p,str[t])>0) first=t+1;
        else
        {
            if(v[t]<v[x]+1) v[t]=v[x]+1;
            if(v[t]>sum) sum=v[t];
            break;
        }
    }
}
void add(int x)
{
    char s[20];
    int len=strlen(str[x]);
    for(int i=0; i<=len; i++)
    {
        strcpy(s,str[x]);
        int j=i;
        for(; str[x][j]!='\0'; j++) s[j+1]=str[x][j];
        s[j+1]='\0';
        for( j=0; j<26; j++)
        {
            s[i]=j+'a';
            dic(x,s);
        }
    }
}
void del(int x)
{
    char s[18];
    for(int i=0; str[x][i]!='\0'; i++)
    {
        int len=0;
        for(int j=0; str[x][j]!='\0'; j++)
            if(j!=i) s[len++]=str[x][j];
        s[len]='\0';
        dic(x,s);
    }
}
void change(int x)
{
    char s[18];
    strcpy(s,str[x]);
    for(int i=0; s[i]!='\0'; i++)
    {
        char c=s[i];
        for(int j=0; j<26; j++)
        {
            s[i]=j+'a';
            dic(x,s);
        }
        s[i]=c;
    }
}
int main()
{
    //freopen("a.txt","r",stdin);
    sum=1;
    n=0;
    while(scanf("%s",str[n])!=EOF) v[n++]=1;
    for(int i=0; i<n-1; i++)
    {
        add(i);
        del(i);
        change(i);
    }
    printf("%d\n",sum);
    return 0;
}


posted @ 2013-05-21 21:28  javawebsoa  Views(243)  Comments(0Edit  收藏  举报