I am trying to solve this question:
http://www.spoj.com/problems/FINDPATH/
Don't know where it's going wrong.
Firstly i am ignoring all the a[i] which are not divisors of destination, i.e., N
I am maintaining a map which maps each number to its parent and distance from root.
Then my idea is that i will be doing a bfs from '1' and then,
I am considering only those (q.top() * a[i]) that are <= N,
Then if queue contains (q.top() * a[i]) update the distance of (q.top() * a[i])
if distance(q.top()) + 1 < distance(q.top() * a[i])
else if the distances are equal then,
if (q.top() < parent(q.top() * a[i]))
then update update parent(q.top() * a[i]) = q.top()
else if queue doesn't contain (q.top() * a[i])
then i am simply pushing it in queue.
Finally if a node N is present in the map then i print the distance and then the path using backtracking.
Here is my code:
int main(){
ll int n, m;
ll int x, top;map<ll int, pair<ll int, ll int>>::iterator it, topit;while(scanf("%lld %lld",&n,&m)!= EOF){
ve(ll int) v;
lp (i,0, m){scanf("%lld",&x);if(n % x ==0) v.pb(x);}
m = v.size();map<ll int, pair<ll int, ll int>> s;
s.insert(mp(1, mp(1,0)));queue<ll int> q;
q.push(1);while(!q.empty()){
top = q.front();
q.pop();
topit = s.find(top);
lp (i,0, m){if(top * v[i]<= n){
it = s.find(top * v[i]);if(it != s.end()){if((*it).second.second >(*topit).second.second +1){(*it).second.second =(*topit).second.second +1;(*it).second.first = top;}elseif((*it).second.second ==(*topit).second.second +1){if(top <(*it).second.first)(*it).second.first = top;}}else{
s.insert(mp(top * v[i], mp(top,(*topit).second.second +1)));
q.push(top * v[i]);}}}}
it = s.find(n);
ve(ll int) ans;
ans.pb(n);if(it == s.end()){
printf("-1\n");}else{
printf("%lld\n",(*it).second.second);while((*it).second.first !=1){
ans.pb((*it).second.first);
it = s.find((*it).second.first);}
ans.pb((*it).second.first);
lpd (i, ans.size()-1,0) printf("%lld ", ans[i]);
printf("\n");}}return0;
}
Note:
1) lp (i, 0, m) : for (int i = 0; i < m; i++)
2) pb : push_back
3) ll : long long
4) lpd(i, n, 0) : for (int i = n; i>= 0; i--)
Is there any error in my approach ?