#include <bits/stdc++.h>
using namespace std;
vector <int> routes[100003];
vector <string> ans;
int path[100003], vis[100003], kk;
map <int, string> M1;
void print_path(int v, int u){
int p = path[v];
kk++;
if(p != u)print_path(p, u);
ans.push_back(M1[p]);
}
void BFS(int src, int dest){
queue <int> Q;
vis[src] = 1;
Q.push(src);
while(!Q.empty()){
int u = Q.front();
Q.pop();
int sz = routes[u].size();
for(int i = 0; i < sz; i++){
int v = routes[u][i];
if(!vis[v]){
vis[v] = 1;
path[v] = u;
Q.push(v);
}
}
}kk = 0;
if(path[dest] == -1)puts("No route");
else print_path(dest, src), ans.push_back(M1[dest]);
int szz = ans.size();
if(path[dest] != -1){
for(int i = 0; i < szz-1; i++)cout << ans[i] << " " << ans[i+1] << endl;
}
}
int main(){
int n, tmp, f = 0;
string start, endd;
while(cin >> n){
map <string, int> M;
int k = 1;
for(int i = 1; i <= n; i++){
cin >> start >> endd;
if(!M[start])M[start] = k, M1[k] = start, k++;
if(!M[endd])M[endd] = k, M1[k] = endd; k++;
routes[M[start]].push_back(M[endd]);
routes[M[endd]].push_back(M[start]);
}
cin >> start >> endd;
memset(path, -1, sizeof(path));
memset(vis, 0, sizeof(vis));
if(f)puts("");
BFS(M[start], M[endd]);
for(int i = 1; i <= n; i++)routes[i].clear();
M.clear(), M1.clear();
ans.clear();
f = 1;
}
return 0;
}
using namespace std;
vector <int> routes[100003];
vector <string> ans;
int path[100003], vis[100003], kk;
map <int, string> M1;
void print_path(int v, int u){
int p = path[v];
kk++;
if(p != u)print_path(p, u);
ans.push_back(M1[p]);
}
void BFS(int src, int dest){
queue <int> Q;
vis[src] = 1;
Q.push(src);
while(!Q.empty()){
int u = Q.front();
Q.pop();
int sz = routes[u].size();
for(int i = 0; i < sz; i++){
int v = routes[u][i];
if(!vis[v]){
vis[v] = 1;
path[v] = u;
Q.push(v);
}
}
}kk = 0;
if(path[dest] == -1)puts("No route");
else print_path(dest, src), ans.push_back(M1[dest]);
int szz = ans.size();
if(path[dest] != -1){
for(int i = 0; i < szz-1; i++)cout << ans[i] << " " << ans[i+1] << endl;
}
}
int main(){
int n, tmp, f = 0;
string start, endd;
while(cin >> n){
map <string, int> M;
int k = 1;
for(int i = 1; i <= n; i++){
cin >> start >> endd;
if(!M[start])M[start] = k, M1[k] = start, k++;
if(!M[endd])M[endd] = k, M1[k] = endd; k++;
routes[M[start]].push_back(M[endd]);
routes[M[endd]].push_back(M[start]);
}
cin >> start >> endd;
memset(path, -1, sizeof(path));
memset(vis, 0, sizeof(vis));
if(f)puts("");
BFS(M[start], M[endd]);
for(int i = 1; i <= n; i++)routes[i].clear();
M.clear(), M1.clear();
ans.clear();
f = 1;
}
return 0;
}
No comments:
Post a Comment