B. Nearest Fraction time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard output 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. Input A single line contains three integers x, y, n (1 ≤ x, y, n ≤ 105). Output Print the required fraction in the format "a/b" (without quotes). Sample test(s) Input 3 7 6 Output 2/5 Input 7 2 4 Output 7/2 這題目,怎麼說呢,思路不多久就想出來了, 枚舉分母,求分子就可以,但是卻是wa,到最後也沒能解決,看數據的時候卻發現 中間過程在計算的時候,數據出現了溢出。哎,杯具了。 [cpp] #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; }