Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

这题好邪门~两种写法差不多,一个过一个不过~求牛人指点迷津~

Posted by Moon_1st at 2011-01-25 16:53:12 on Problem 1079
第一种:WA的,还没轮到判PE呢= =!:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;

int gcd(int a, int b)
{
    if(b == 0)  return a;
    else  return gcd(b, a%b);
}

double Abs(double x)
{
    if(x < 0)  return -x;
    else  return x;
}

double Round(double x)
{
    double tmp1, tmp2;
    tmp1 = floor(x);
    tmp2 = ceil(x);
    if(Abs(x-tmp1) > Abs(x-tmp2))  return tmp2;
    else  return tmp1;
}

int main()
{
    int x, y, d, flag, i;
    double xx, yy, ratio, pre, tmp;
    while(scanf("%d%d", &x, &y) != EOF)
    {
        d = gcd(x, y);
        x /= d;
        y /= d;
        if(x >= y)  flag = 0;
        else  flag = 1;
        if(flag == 1)  swap(x, y);
        xx = double(x);
        yy = double(y);
        ratio = xx / yy;
        pre = 1000000.0;
        for(i = 1; i <= y; i++)
        {
            yy = (double)i;
            xx = Round(yy*ratio);
            tmp = Abs(xx/yy-ratio);
            if(pre <= tmp)  continue;
            else
            {
                pre = tmp;
                if(flag == 0)
                    printf("%.0f/%.0f\n", xx, yy);
                else
                    printf("%.0f/%.0f\n", yy, xx);
            }
        }
        printf("\n");
    }
    return 0;
}

第二种,AC的~:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;

int gcd(int a, int b)
{
    if(b == 0)  return a;
    else  return gcd(b, a%b);
}

double Abs(double x)
{
    if(x < 0)  return -x;
    else  return x;
}

int Round(double x)
{
    int t = (int)x;
    if(x-t >= 0.5)  t++;
    return t;
}

int main()
{
    int x, y, d, i, cc = 0;
    double ratio, pre, tmp;
    while(scanf("%d%d", &x, &y) != EOF)
    {
        if(cc)  printf("\n");
        d = gcd(x, y);
        x /= d;
        y /= d;
        ratio = (double)x / y;
        pre = 1000000.0;
        for(i = 1; i <= y; i++)
        {
            tmp = (double)x*i/y;
            d = Round(tmp);
            tmp = Abs((double)d/i - ratio);
            if(tmp < pre)
            {
                pre = tmp;
                printf("%d/%d\n", d, i);
            }
        }
        cc++;
    }
    return 0;
}

这两者区别有多大,可有牛人现身指点迷津??

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator