Shortest path from 1 to n

PROBLEM :

Consider a directed graph whose vertices are numbered from 1 to n. There is an edge from a vertex i to a vertex j iff either j = i + 1 or j = 3i. The task is to find the minimum number of edges in a path in G from vertex 1 to vertex n.

Input:  The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.

Each test case contains a value of n.

Output:  Print the number of edges in the shortest path from 1 to n.
Constraints: 1<=T<=30
Example:  1<=n <=1000

Example:
Input:
2
9
4

Output:
2
2

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
int main()
{
    int t ;
    cin>>t ;
    while(t--)
    {
        int no ;
        cin>>no ;
       
        int count=0 ;
       
        while(no!=1)
        {
            if(no%3==0)
                no=no/3 ;
            else
                no=no-1 ;
               
            count++ ;
        }
        cout<<count<<endl ;
    }
return 0;
}

--------------------------------------------------------------------------------

Comments

Post a Comment

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )