1684: [Usaco2005 Oct]Close Encounter
Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 547 Solved: 281
[ Submit][ Status][ Discuss]
Description
Lacking even a fifth grade education, the cows are having trouble with a fraction problem from their textbook. Please help them. The problem is simple: Given a properly reduced fraction (i.e., the greatest common divisor of the numerator and denominator is 1, so the fraction cannot be further reduced) find the smallest properly reduced fraction with numerator and denominator in the range 1..32,767 that is closest (but not equal) to the given fraction. 找一个分数它最接近给出一个分数. 你要找的分数的值的范围在1..32767
Input
* Line 1: Two positive space-separated integers N and D (1 <= N < D <= 32,767), respectively the numerator and denominator of the given fraction
Output
* Line 1: Two space-separated integers, respectively the numerator and denominator of the smallest, closest fraction different from the input fraction.
Sample Input
Sample Output
中文翻译少了一句话:两个分数不能相等
一开始以为答案就是32767*N/D和32767或32767*N/D+1和32767,后来发现分母不一定是32767
所以要暴力分母然后求和最小
这题貌似还卡个精度
#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
#define LD long double
int main(void)
{
LD ans;
int n, m, i, t, p, q;
scanf("%d%d", &m, &n);
ans = 100000;
for(i=2;i<=32767;i++)
{
t = i*m/n;
if(fabs((LD)t/i-(LD)m/n)<ans && t*n!=i*m)
{
p = t, q = i;
ans = fabs((LD)t/i-(LD)m/n);
}
t++;
if(fabs((LD)t/i-(LD)m/n)<ans && t*n!=i*m)
{
p = t, q = i;
ans = fabs((LD)t/i-(LD)m/n);
}
}
printf("%d %d\n", p, q);
return 0;
}