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;
}
--------------------------------------------------------------------------------
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;
}
--------------------------------------------------------------------------------
losiMplecpu Melanie Martinez https://marketplace.visualstudio.com/items?itemName=stinlime-mi.Blood-Impact-gratuita
ReplyDeletetralegberging
0trantupeke Kimberly Jensen https://www.oaks-family-care.org/profile/Nagoor-Hanifa-Songs-Free-Download-Tamil-New-Moviegolkes-VERIFIED/profile
ReplyDeleteprovevupgue
xapeQla_no Melanie Mccallister Awesome
ReplyDeleteclick here
Best
pitslagardsa
can you do this with time complexity O(log(n))
ReplyDelete