Monday, May 26, 2014

SPOJ Problem NG0FRCTN


Fractions on Tree

Explanation:

A simple problem which can be solved using recursion.
Our base case will be n = 1, for which numerator will be 1, i.e., (num = 1) and denominator also 1, (den = 1).
For n > 1, we find the value for its parent, say (num / den) by finding the value of n / 2.
Now, 
    if the child is left child, we add numerator to the denominator (den = den + num).
   else, we add denominator to the numerator (num = num + den).
Finally, return the result (num / den).

Solution:

#include<cstdio>
#include<iostream>
#include<vector>

typedef long long int LLD;
typedef unsigned long long int LLU;

using namespace std;

vector<LLD> find_value(LLD n){

    // res[0] denotes numerator and res[1] denotes denominator.
    vector<LLD> res;
    res.resize(2);

    // Base case with n = 1. 
    if(n == 1){
        res[0] = 1;
        res[1] = 1;
        return res;
    }

    // Find the value for parent in res.
    res = find_value(n >> 1);

    // Check for left child.
    if(n == ((n >> 1) << 1))
        res[1] += res[0];
    // Check for right child.
    else
        res[0] += res[1];
    return res;
}

int main(){
 
    LLD n;
    vector<LLD> res;
    res.resize(2);
    while(true){
        scanf("%lld", &n);
        if(!n)
            break;
        res = find_value(n);
        printf("%lld/%lld\n", res[0], res[1]);
    }
    return 0;
}

Any suggestions are welcome.

No comments:

Post a Comment

SPOJ Problem ONEZERO

Ones and zeros Explanation: A very good problem to practice BFS skills. I think that much hint is good to give the problem a shot. An...