#include<bits/stdc++.h> using namespace std; #define pb push_back class Graph{ int V; list<int>*adj; public: Graph(int V); ~Graph(); void addEdge(int u, int v); int BFS(int s,int dest); }; Graph::Graph(int V) //construtor { this->V=V; adj=new list<int >[V]; } Graph::~Graph() //destructor { delete []adj; } void Graph::addEdge(int u,int v) { adj[u].pb(v); adj[v].pb(u); } int Graph::BFS(int s,int dest) { bool visited[V]; int level[V]; memset(visited,false,sizeof(visited)); list<int>q; list<int>::iterator i; q.pb(s); visited[s]=true; level[s]=0; while (!q.empty()) { s=q.front(); q.pop_front(); for (i=adj[s].begin();i!=adj[s].end();++i) { if (!visited[*i]) { q.pb(*i); visited[*i]=true; level[*i]=level[s]+1; if (*i==dest) return level[*i]; } } } return -1; } bool ifSuccessive(string a,string b) { if (a.length()!=b.length()) return false; int dif=0,l=a.length(); for (int i=0;i<l;i++) if (a[i]!=b[i]) dif++; return dif==1?true:false; } int main() { int tc; scanf("%d",&tc); while (tc--) { string s; map<string,int>msi; vector<string>v; int k=0; while (cin>>s) { if (s=="*") break; v.pb(s); msi[s]=k++; } Graph g(k); for (int i=0;i<k;i++) for (int j=i+1;j<k;j++) if (ifSuccessive(v[i],v[j])) g.addEdge(msi[v[i]],msi[v[j]]); string start,to,line; size_t pos; getline(cin,line); getline(cin,line); while(line != ""){ pos = line.find(" "); start = line.substr(0,pos); to = line.substr(pos+1,line.size()); cout<<start<<" "<<to<<" "<<g.BFS(msi[start],msi[to])<<endl; if(!getline(cin,line)) break; } if (tc) cout<<endl; } return 0; }
Wednesday, August 24, 2016
UVA 429 - Word Transformation-Solution
Unknown
Studying at Shahjalal University of Science and Technology, Sylhet.
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment