1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| #include<bits/stdc++.h> #define ll long long #define ull unsigned long long #define maxn 405 #define put() putchar('\n') #define Tp template<typename T> #define Ts template<typename T,typename... Ar> using namespace std; Tp void read(T &x){ int f=1;x=0;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') {x=x*10+c-'0';c=getchar();} x*=f; } namespace Debug{ Tp void _debug(char* f,T t){cerr<<f<<'='<<t<<endl;} Ts void _debug(char* f,T x,Ar... y){while(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);} #define gdb(...) _debug((char*)#__VA_ARGS__,__VA_ARGS__) }using namespace Debug; #define fi first #define se second #define mk make_pair const int mod=1e9+7; int power(int x,int y=mod-2) { int sum=1; while (y) { if (y&1) sum=sum*x%mod; x=x*x%mod;y>>=1; } return sum; } int n,m; vector<int>to[maxn][27],pre[maxn][27]; int f[maxn][maxn],g[maxn][maxn][27]; pair<int,int> pg[maxn][maxn][27]; struct yyy { int l,r,c; yyy (int a=0,int b=0,int d=0) { l=a;r=b;c=d; } }pf[maxn][maxn]; queue<pair<int,int> >q1; queue<yyy>q2; int Ans[100005]; void print(int x,int y) { int l=0,r=f[x][y]+1,c,tmp1,tmp2,len=f[x][y],i; while (l+1<r) { Ans[++l]=pf[x][y].c; tmp1=pf[x][y].l,tmp2=pf[x][y].r; c=pf[x][y].c,x=tmp1,y=tmp2; if (l+1>=r) break; Ans[--r]=c; tmp1=pg[x][y][c].fi,tmp2=pg[x][y][c].se; x=tmp1,y=tmp2; } for (i=1;i<=len;i++) putchar(Ans[i]+'a'); } signed main(void){ int i,j,x,y,z,k;char ch; memset(f,0x3f,sizeof(f)); memset(g,0x3f,sizeof(g)); read(n);read(m); for (i=1;i<=n;i++) f[i][i]=0,q1.push(mk(i,i)); for (i=1;i<=m;i++) { read(x);read(y);ch=getchar(); to[x][ch-'a'].push_back(y); pre[y][ch-'a'].push_back(x); f[x][y]=1;pf[x][y]=yyy(0,0,ch-'a'); q1.push(mk(x,y)); } while (!q1.empty()||!q2.empty()) { if (!q1.empty()&&(q2.empty()||f[q1.front().fi][q1.front().se]<=g[q2.front().l][q2.front().r][q2.front().c])) { x=q1.front().fi,y=q1.front().se;q1.pop(); for (i=0;i<26;i++) { for (auto tmp:to[y][i]) if (g[x][tmp][i]>f[x][y]+1) { g[x][tmp][i]=f[x][y]+1; pg[x][tmp][i]=mk(x,y); q2.push(yyy(x,tmp,i)); } } } else { x=q2.front().l,y=q2.front().r,z=q2.front().c;q2.pop(); for (auto tmp:pre[x][z]) if (f[tmp][y]>g[x][y][z]+1) { f[tmp][y]=g[x][y][z]+1; pf[tmp][y]=yyy(x,y,z); q1.push(mk(tmp,y)); } } } read(k);read(x);k--; while (k--) { read(y); if (f[x][y]<=1e9) printf("%d ",f[x][y]),print(x,y),put(); else puts("-1"); x=y; } return 0; }
|