2013年9月18日 星期三

UVA 12575 - Sin Cos Problem

Problem link

Keyword: math

Algorithm:

It is actually a math problem and with not much to do with programming.
Here's how to find the maximum value and the optimal theta.

Greatest value: always equal to the square root of a*a + b*b.

Theta: (represented by x)

let root = sqrt( a*a + b*b )
a * sin theta + b * cos theta
= root ( a/root * sin theta + b/root * cos theta )
= root sin( theta+x )
where cos x = a / root, and sin x = b / root

With these 2 conditions, you can find x easily, and x is just what you want.
Notice when a = b = 0, this formula leads to a wrong answer.

Code:
#include<cstdio>
#include<cmath>

int main()
{
    int t;
    double a, b, pi = acos( -1 ), eps = 1e-14;
    scanf( "%d", &t );

    while( t-- )
    {
        scanf( "%lf %lf", &a, &b );
        double len = sqrt( a*a + b*b ), theta = len? acos( a / len ) : pi / 2;
        if( b < 0 )
            theta = 2 * pi - theta;
        printf( "%.2lf %.2lf\n", ( theta > pi / 2? 2.5 * pi - theta : pi / 2 - theta )+eps, len+eps );
    }

    return 0;
}

沒有留言:

張貼留言