You are given three positive integers x, y, n. Your task is to find the nearest fraction to fraction
whose denominator is no more than
n.
Formally, you should find such pair of integers a, b
(1 ≤ b ≤ n; 0 ≤ a) that the value
is as minimal as possible.
If there are multiple "nearest" fractions, choose the one with the minimum denominator. If there are multiple "nearest" fractions with the minimum denominator, choose the one with the minimum numerator.
A single line contains three integers x, y, n (1 ≤ x, y, n ≤ 105).
Print the required fraction in the format "a/b" (without quotes).
3 7 6
2/5
7 2 4
7/2
这题目,怎么说呢,思路不多久就想出来了, 枚举分母,求分子就可以,但是却是wa,到最后也没能解决,看数据的时候却发现 中间过程在计算的时候,数据出现了溢出。哎,杯具了。
#include <stdio.h> #include <string.h> #include <math.h> struct num { int zi,mu; double val; }res[1000000]; int cmp(const void *e,const void *f) { struct num *p1=(struct num *)e; struct num *p2=(struct num *)f; if(fabs(p1->val-p2->val)<=1e-15) { if(p1->mu>p2->mu) { return 1; }else if(p1->mu<p2->mu) { return -1; }else { if(p1->zi>p2->zi) { return 1; }else if(p1->zi<p2->zi) { return -1; }else { return 0; } } } if(p1->val>p2->val) { return 1; }else { return -1; } } int main() { int x,y,n,s,i,top,t; long long int zhong; double mod; while(scanf("%d %d %d",&x,&y,&n)!=EOF) { top=0; for(i=1;i<=n;i++) { zhong=((long long int)i*(long long int)x); mod=(double)(zhong)/y; t=(int)(mod+0.01); res[top].mu=i; res[top].zi=t; res[top++].val=fabs((double)x/(double)y-(double)t/(double)i); res[top].mu=i; res[top].zi=t+1; res[top++].val=fabs((double)x/(double)y-(double)(t+1)/(double)i); res[top].mu=i; res[top].zi=t+2; res[top++].val=fabs((double)x/(double)y-(double)(t+2)/(double)i); res[top].mu=i; if(t-1>=0) { res[top].mu=i; res[top].zi=t-1; res[top++].val=fabs((double)x/(double)y-(double)(t-1)/(double)i); } if(t-2>=0) { res[top].mu=i; res[top].zi=t-2; res[top++].val=fabs((double)x/(double)y-(double)(t-2)/(double)i); } } qsort(res,top,sizeof(res[0]),cmp); printf("%d/%d\n",res[0].zi,res[0].mu); } return 0; }