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
| #include<algorithm> #include<iostream> #include<iomanip> #include<cstring> #include<cstdlib> #include<vector> #include<cstdio> #include<cmath> #include<queue> using namespace std; inline const int Get_Int() { int num=0,bj=1; char x=getchar(); while(x<'0'||x>'9') { if(x=='-')bj=-1; x=getchar(); } while(x>='0'&&x<='9') { num=num*10+x-'0'; x=getchar(); } return num*bj; } const int maxn=405; int n,m,f[maxn][maxn],g[maxn][maxn][26]; bool map[maxn][maxn][26]; queue<pair<pair<int,int>,int> >Q; vector<int>from[maxn][26],to[maxn][26]; void AddEdge(int x,int y,int c) { from[y][c].push_back(x); to[x][c].push_back(y); } int main() { n=Get_Int(); m=Get_Int(); memset(f,-1,sizeof(f)); memset(g,-1,sizeof(g)); for(int i=1; i<=n; i++) { f[i][i]=0; Q.push(make_pair(make_pair(i,i),-1)); } for(int i=1; i<=m; i++) { int x=Get_Int(),y=Get_Int(); char c=' '; while(!isalpha(c))c=getchar(); map[x][y][c-'a']=1; } for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) if(i!=j) { bool bj=0; for(int c=0; c<26; c++) if(map[i][j][c]) { AddEdge(i,j,c); bj=1; break; } if(bj) { f[i][j]=1; Q.push(make_pair(make_pair(i,j),-1)); } } while(!Q.empty()) { pair<pair<int,int>,int>Now=Q.front(); Q.pop(); int x=Now.first.first,y=Now.first.second,c=Now.second; if(c==-1) { for(int i=0; i<26; i++) for(int Next:to[y][i]) if(g[x][Next][i]==-1) { g[x][Next][i]=f[x][y]+1; Q.push(make_pair(make_pair(x,Next),i)); } } else for(int Next:from[x][c]) if(f[Next][y]==-1) { f[Next][y]=g[x][y][c]+1; Q.push(make_pair(make_pair(Next,y),-1)); } } int q=Get_Int(),last=Get_Int(); for(int i=2; i<=q; i++) { int x=Get_Int(); printf("%d\n",f[last][x]); last=x; } return 0; }
|