HACKER RANK Algorithms - Implementation - Manasa and Stones - Solution.'C'

                                   Algorithms - Implementation - Manasa andStones - Solution
Problem Statement
Manasa is out on a hike with friends. She finds a trail of stones with numbers on them. She starts following the trail and notices that two consecutive stones have a difference of either aor b. Legend has it that there is a treasure trove at the end of the trail and if Manasa can guess the value of the last stone, the treasure would be hers. Given that the number on the first stone was 0, find all the possible values for the number on the last stone.
Note: The numbers on the stones are in increasing order.
Input Format 
The first line contains an integer T, i.e. the number of test cases. T test cases follow; each has 3 lines. The first line contains n (the number of stones). The second line contains a, and the third line contains b.
Output Format 
Space-separated list of numbers which are the possible values of the last stone in increasing order.
Constraints 
1T10 
1n,a,b103
Sample Input
2
3 
1
2
4
10
100
Sample Output
2 3 4 
30 120 210 300 
Explanation
All possible series for the first test case are given below:
  1. 0,1,2
  2. 0,1,3
  3. 0,2,3
  4. 0,2,4
Hence the answer 2 3 4.
Series with different number of final steps for second test case are the following:
  1. 0, 10, 20, 30
  2. 0, 10, 20, 120
  3. 0, 10, 110, 120
  4. 0, 10, 110, 210
  5. 0, 100, 110, 120
  6. 0, 100, 110, 210
  7. 0, 100, 200, 210
  8. 0, 100, 200, 300
Hence the answer 30 120 210 300.

Solution:

#include <stdio.h>
 
int main() {
    int i;
    int n, a, b, t;
    int c[1000] = { 0, };
 
    scanf("%d", &t);
 
    while (t--){
        scanf("%d", &n);
        scanf("%d", &a);
        scanf("%d", &b);
 
        for (i = 0; i < n; i++){
            if (a == b)
            {
                printf("%d ", a*(n - 1));
                break;
            }
            else if (a>b)
                c[i] = (b*(n - 1 - i)) + (a*i);
            
            else
                c[i] = (a * (n - i - 1)) + (b*i);
            printf("%d ",c[i]);
        }
 
        printf("\n");
    }
    return 0;
}

Thanks for Visiting, Hope this helps you....

Comments

Popular Posts