C
Programming and Technical
Programming
Program
A rabbit walk is defined by a sequence of jumps which starts from a
location and returns back to the starting location. We can repesent such
a Rabbit walk by an array A of n numbers, where A[i] denotes the next
array index to which the rabbit should jumps from the location i.
For example, the sequence: 2 3 4 5 0 1 indicates that the Rabbit follows
the jump sequence: 0->2, 2->4, 4->0 and stops.
Your also given another array B of N numbers, such that
B[i] denotes the number of carrots available at location i.
Your task is to compute the number of carrots that a rabbit can collect
when it makes rabbit walk(s) from various start position(s).
A sample input is provided for more clarification(s).
Input:
The first line will contain a single integer N which is the size of the
array (2<= N <= 10000).
The next line contains a series of N integers which define the array A.
The next line contains a series of N integers which define the array B.
You can be assured that all the calculations fit into a 32 bit signed
integer type(int in C).
The input is given such that, a rabbit walk will always exist with
start position as 0.
Output:
It should contain the number of carrots collected
when 0 is treated as the start location.
Sample Input:
6
2 2 2 2 -4 -4
2 3 6 3 0 1
Sample Output:
8
Read Solution (Total 2)
-
- #include
#include
#include
int rabbitWalk(int * arr,int n,int *Barr);
int main()
{
int A[] = {2,3,5,4,0,1},n=6,B[]= {2,2,3,2,1,3};
int numCarrots = rabbitWalk(A,n,B);
printf("nNumber of carrots : %d n",numCarrots);
return 0;
}
int rabbitWalk(int * arr,int n,int *Barr)
{
int i=0,count = 0 ;
while(1)
{
//printf("%c -->",charArray[i]);
i = arr[i];
count = count + Barr[i];
if(i == 0)
{
count = count + Barr[i]; // Counting the carrots at 0 position again . This can bre removed if required.
//printf("%c",charArray[i]);
break;
}
}
return count;
} - 10 years agoHelpfull: Yes(2) No(0)
- void main()
{
int a[6]={2,3,5,4,0,1},n=6,b[] = {2,2,3,2,1,3},count=0,i=0;
while(1){
count += b[a[i]];
i=a[i];
if(i==0)break;
}
printf("%d",count);
}
- 10 years agoHelpfull: Yes(0) No(0)
C Other Question