|
| 1 | +typedef unsigned int uint; |
| 2 | +const int N=5005,L0=10,L=N*L0; const uint mul=131; |
| 3 | +int vis[N],q[N],v1; uint hsh[N],mul1[L0]; |
| 4 | +vector<int> v[L]; |
| 5 | +namespace Hash{ |
| 6 | + const uint S=16,S1=32-S,M=1996090921; |
| 7 | + struct node{ |
| 8 | + int x,t; |
| 9 | + vector<int> *y; |
| 10 | + }h[(1<<S)+1005]; |
| 11 | + int T=1; |
| 12 | + inline void insert(int x,int y){ |
| 13 | + node *p=h+((uint)x*M>>S1); |
| 14 | + for (;p->t==T;++p) |
| 15 | + if (p->x==x){p->y->push_back(y); return;} |
| 16 | + p->t=T; p->x=x; p->y=v+(v1++); p->y->push_back(y); |
| 17 | + } |
| 18 | + inline vector<int>** find(int x){ |
| 19 | + for (node *p=h+((uint)x*M>>S1);p->t==T;++p) |
| 20 | + if (p->x==x)return &p->y; |
| 21 | + return 0; |
| 22 | + } |
| 23 | +} using namespace Hash; |
| 24 | + |
| 25 | +class Solution { |
| 26 | +public: |
| 27 | + int ladderLength(string beginWord, string endWord, vector<string>& w) { |
| 28 | + for (int i=0;i<v1;++i)v[i].clear(); |
| 29 | + int n=w.size(); v1=0; ++T; |
| 30 | + for (int i=0;i<n-1;++i) |
| 31 | + if (w[i]==endWord)swap(w[i],w[n-1]); |
| 32 | + if (w[n-1]!=endWord)return 0; |
| 33 | + w.push_back(beginWord); ++n; |
| 34 | + mul1[0]=1; for (int i=1;i<L0;++i)mul1[i]=mul1[i-1]*mul; |
| 35 | + for (int i=0;i<n;++i){ |
| 36 | + int l=w[i].size(); uint h0=0; |
| 37 | + for (char *p=&w[i][0],*end=p+l;p!=end;++p)h0=h0*mul+*p; |
| 38 | + for (char *p=&w[i][0],*end=p+l;p!=end;++p){ |
| 39 | + uint h1=h0-*p*mul1[end-1-p]; |
| 40 | + insert(h1,i); |
| 41 | + } |
| 42 | + hsh[i]=h0; |
| 43 | + } |
| 44 | + for (int i=0;i<n;++i)vis[i]=0; vis[n-1]=1; |
| 45 | + int l=0,r=1,ans=1; q[0]=n-1; |
| 46 | + while (l<r){ |
| 47 | + int r1=r; ++ans; |
| 48 | + for (;l<r;++l){ |
| 49 | + int i=q[l]; uint h0=hsh[i]; |
| 50 | + for (char *p=&w[i][0],*end=p+w[i].size();p!=end;++p){ |
| 51 | + uint h1=h0-*p*mul1[end-1-p]; |
| 52 | + vector<int>** pt=find(h1); |
| 53 | + if (*pt){ |
| 54 | + vector<int> &vec=*(*pt); |
| 55 | + for (int j:vec) |
| 56 | + if (!vis[j]){ |
| 57 | + q[r1++]=j,vis[j]=1; |
| 58 | + if (j==n-2)return ans; |
| 59 | + } |
| 60 | + *pt=0; |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + l=r; r=r1; |
| 65 | + } |
| 66 | + return 0; |
| 67 | + } |
| 68 | +}; |
| 69 | + |
| 70 | +//IO |
| 71 | +int _IO=[](){ |
| 72 | + ios::sync_with_stdio(0); |
| 73 | + cin.tie(0); //cout.tie(0); |
| 74 | + return 0; |
| 75 | +}(); |
| 76 | + |
0 commit comments