Application of breadth first search

Price: $15 USD

Question description

Type your programming questio

0 down vote favorite

I am trying to solve this question:
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 ( * a[i]) that are <= N,
Then if queue contains ( * a[i]) update the distance of ( * a[i])
if distance( + 1 < distance( * a[i])
else if the distances are equal then,
if ( < parent( * a[i]))
then update update parent( * a[i]) =
else if queue doesn't contain ( * 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;
        top = q.front();
        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("%lld\n",(*it).second.second);while((*it).second.first !=1){
            it = s.find((*it).second.first);}
        lpd (i, ans.size()-1,0) printf("%lld ", ans[i]);


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 ?

n here...

Tutor Answer

(Top Tutor) Studypool Tutor
School: UIUC
Studypool has helped 1,244,100 students
Ask your homework questions. Receive quality answers!

Type your question here (or upload an image)

1820 tutors are online

Brown University

1271 Tutors

California Institute of Technology

2131 Tutors

Carnegie Mellon University

982 Tutors

Columbia University

1256 Tutors

Dartmouth University

2113 Tutors

Emory University

2279 Tutors

Harvard University

599 Tutors

Massachusetts Institute of Technology

2319 Tutors

New York University

1645 Tutors

Notre Dam University

1911 Tutors

Oklahoma University

2122 Tutors

Pennsylvania State University

932 Tutors

Princeton University

1211 Tutors

Stanford University

983 Tutors

University of California

1282 Tutors

Oxford University

123 Tutors

Yale University

2325 Tutors