UVA Problem 10347 – Medians Solution

UVA Problem 10347 – Medians Solution:


Click here to go to this problem in uva Online Judge.

Solving Technique:

This is a simple geometrical problem. We can use Heron’s formula to calculate the area.

Use double for safety. Print 3 places after decimal point. If the area is invalid then print -1.000 ( with 3 Zeros ) after decimal point. This may be a reason for WA.

I have provided two codes. One of them uses fread and string stream ( include sstream ) to take and process input. I have commented this code for easier understanding. The other code is with out fread, stringstream and not commented.

Important:  Be sure to add or print a new line after each output unless otherwise specified. The outputs should match exactly because sometimes even a space character causes the answer to be marked as wrong answer.


Critical Inputs:

 1  2  3
 5  9  4
 3  2  3
 4  5  3
-3 -3 -3

 


Output:

-1.000
-1.000
 3.771
 8.000
 5.196

Code:

/**
 * @author  Quickgrid ( Asif Ahmed )
 * @link    https://quickgrid.wordpress.com
 */

#include<iostream>
#include<cstdio>
#include<sstream>
#include<cmath>

static char buffer[32768];

int main(){
    double a,b,c,s;

    /**
     * @brief Read file from stdin and create string stream of buffer
     */
	fread(buffer, 1, sizeof buffer, stdin);
	std::stringstream ss(buffer);

	while (ss >> a >> b >> c){

        /**
         * Heron's Formula: s, is semi perimeter
         */
        s = (a + b + c) / 2.0;

        /**
         * Heron's Formula: area, of a triangle
         */
        double area = (4.0 / 3.0) * sqrt(s * (s - a) * (s - b) * (s - c));

        /**
         * If area is not valid then print -1, otherwise print area
         */
        area > 0 ? printf("%0.3lf\n", area) : printf("-1.000\n");
	}
	return 0;
}

Code ( Without fread() and stringstream() ):

/**
 * @author  Quickgrid ( Asif Ahmed )
 * @link    https://quickgrid.wordpress.com
 */

#include<iostream>
#include<cstdio>
#include<sstream>
#include<cmath>

using namespace std;

int main(){
    double a,b,c,s;

	while (scanf("%lf%lf%lf", &a, &b, &c) == 3){

        double s = (a + b + c) / 2.0;
        double area = (4.0 / 3.0) * sqrt(s * (s - a) * (s - b) * (s - c));

        if(area > 0)
            printf("%0.3lf\n", area);
        else
            printf("-1.000\n");

	}
	return 0;
}

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s