Sunday, December 25, 2016

UVA 762 - We Ship Cheap

#include <bits/stdc++.h>
#define sf scanf
#define pf printf
using namespace std;
map<string, bool>visited;
void bfs(string start , string end , map<string , vector<string> >mp)
{
vector<pair<string, string> >vp;
queue<string>q;
q.push(start);
visited[start] = true;
bool flag = false;
while(!q.empty()){
string top = q.front();
q.pop();
for(int i=0; i<mp[top].size(); i++){
if(!visited[mp[top][i]]){
visited[mp[top][i]] = true;
if(mp[top][i] != end){
vp.push_back(make_pair(top , mp[top][i]));
q.push(mp[top][i]);
}else if(mp[top][i] == end){
flag = true;
vp.push_back(make_pair(top , mp[top][i]));
break;
}
}
}
if(flag)break;
}
if(!flag && q.empty())cout << "No route\n";
else{
for(int i=0; i<vp.size(); i++)
cout << vp[i].first<< ' '<<vp[i].second<<'\n';
}

}
int main()
{
ios_base::sync_with_stdio(0);
int t;
bool first = true;
while(cin >> t){
if(!first)cout <<'\n';
first = false;
map<string , vector<string> > mp;
visited.clear();
while(t--){
string u , v;
cin >> u >> v;
mp[u].push_back(v);
mp[v].push_back(u);
}
string start, end;
cin >> start >> end;
bfs(start , end , mp);
}
}

4 comments:

  1. your solution is giving wrong answer

    ReplyDelete
    Replies
    1. Hi, I have submitted this solution again using c++ and it's accepted on uva site.

      Delete
  2. you made so many mistakes, you should correct it

    ReplyDelete
    Replies
    1. Can you please tell me where the mistakes are?

      Delete