POJ 1079 : Ratio - 分数逼近
来源:互联网 发布:java 自定义属性 编辑:程序博客网 时间:2024/05/24 04:07
解法二:#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
int main(){
int i,p,q,pt,a,b;
while(~scanf("%d%d",&a,&b)){
p=1;
q=0;
for(i=1;i<=b;i++){
pt=(int)((double)(i*a)/(double)b+0.5);
if(q*abs(a*i-b*pt)<i*abs(a*q-b*p)){
p=pt;
q=i;
printf("%d/%d\n",p,q);
}
if(a*q==b*p) break;
}
puts("");
}
return 0;
}
代码
#include <cstdio>
#include <iostream>
#include <cmath>
using namespace std;
typedef long long INT;
typedef struct{ // num/den
INT num,den;
}frac;
int gcd(INT a,INT b){
INT t;
if (a<0)
a=-a;
if (b<0)
b=-b;
if (!b)
return a;
while (t=a%b)
a=b,b=t;
return b;
}
void simplify(frac& f){ //simplify
int t;
if (t=gcd(f.num,f.den))
f.num/=t,f.den/=t;
else
f.den=1; //num=0
}
frac f(INT n,INT d,INT s=1){ //init fraction
frac ret;
if (d<0)
ret.num=-n,ret.den=-d;
else
ret.num=n,ret.den=d;
if (s)
simplify(ret);
return ret;
}
int fraqcmp(frac a,frac b){
int g1=gcd(a.den,b.den),g2=gcd(a.num,b.num);
if (!g1||!g2)
return 0;
return b.den/g1*(a.num/g2)-a.den/g1*(b.num/g2);
}
frac add(frac a,frac b){
INT g1=gcd(a.den,b.den),g2,t;
if (!g1)
return f(1,0,0);
t=b.den/g1*a.num+a.den/g1*b.num;
g2=gcd(g1,t);
return f(t/g2,a.den/g1*(b.den/g2),0);
}
frac sub(frac a,frac b){
return add(a,f(-b.num,b.den,0));
}
void printfra(frac a){
printf("%INTd/%INTd\n",a.num , a.den);
}
int main(){
frac fra_a , fra_t1, dis , fsub;
int na, nb;
while( scanf("%d %d",&na,&nb) != EOF)
{
fra_a = f(na, nb , 1);
dis.den = 1;
dis.num = floor(fra_a.num * ( (double)(1 ) / fra_a.den) + 0.5);
printfra( dis );
dis = sub(fra_a , dis);
if(dis.num < 0 )dis.num = -dis.num;
for(int i=2 ; i<fra_a.den ; i++)
{
fra_t1.den = i;
fra_t1.num =floor( fra_a.num *( (double)( i ) / fra_a.den) + 0.5);
INT ret ;
fsub = sub(fra_t1, fra_a);
if(fsub.num < 0)fsub.num = -fsub.num;
ret = fraqcmp(dis , fsub);
if( ret > 0)
{
printfra(fra_t1);
dis = fsub;
}
}
printfra(fra_a);
puts("");
}
return 0;
}
- POJ 1079 : Ratio - 分数逼近
- poj 1079 Ratio
- POJ 1079 Ratio 笔记
- poj 1079 Ratio 模拟
- Poj 1650 & Zoj 1601 Integer Approximation (追赶法,分数逼近实数)
- 1079 Ratio
- POJ 3039 搜索??? (逼近)
- poj 3273 (二分法逼近)
- POJ 3925 Minimal Ratio Tree
- POJ 3925 Minimal Ratio Tree
- C++分数的表达,C++的<ratio>头文件
- HDU-6070 Dirt Ratio(二分+线段树+分数规划)
- HDU 6070 Dirt Ratio【分数规划】【线段树】
- ratio
- ratio
- Poj 2456 Aggressive cows (二分逼近)
- POJ 3104 Drying(二分逼近)
- POJ 3122 Pie(二分逼近)
- Openstack Nova Failed to allocate network(s)
- POJ 3243: Clever Y 求A^X = B (mod C) / BabyStep_GiantStep
- POJ 1023 : The Fun Number System - 二进制
- LeetCode-Search Insert Position
- POJ 1995/ ZOJ 2150 : Raising Modulo Numbers - 快速幂取模
- POJ 1079 : Ratio - 分数逼近
- 优化的选择排序和折半查找法
- CDH5.3集群安装笔记-环境准备(2)
- POJ 2142 : The Balance-解不定方程,一元线性同余
- POJ 1305:Fermat vs. Pythagoras - 勾股定理/毕达哥拉斯三元组
- POJ 1320:Street Numbers——佩尔方程
- POJ 2262/ ZOJ 1951:Goldbach\'s Conjecture - 筛法打素数表
- 2015年10大web预测
- POJ 2909 / ZOJ 1657 : Goldbach\'s Conjecture - 筛法打素数表