现在的位置: 首页 > 综合 > 正文

[hoj 1076]Ordered Fractions[Farey序列]

2018年02月23日 ⁄ 综合 ⁄ 共 776字 ⁄ 字号 评论关闭

生成分母不大于N的Farey序列.

这是递归求法.

用扩展欧几里得定理可以求紧邻着的下一项,

公式 K1*L2 - K2*L1 = 1

但是目前还没有学习它...

#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
int n;
typedef struct node
{
    int up,down;
    double val;
}node;
bool cmp(node a, node b)
{
    return a.val<b.val;
}
vector<node> v;
int gcd(int x,int y)
{
    if(!x)  return y;
    if(x<y)
    {
        return gcd(y%x,x);
    }
    return gcd(x%y,y);
}
void build(int a, int b, int x, int y)
{
    int p = a+x;
    int q = b+y;
    int tmp = gcd(p,q);//注意要化成最简
    p /= tmp;
    q /= tmp;
    if(q<=n)
    {
        build(a,b,p,q);
        v.push_back((node){p,q,(double)p/q});
        build(p,q,x,y);
    }
}

int main()
{
    while(scanf("%d",&n)==1)
    {
        while(!v.empty())   v.pop_back();
        v.push_back((node){0,1,0.0});
        v.push_back((node){1,1,1.0});
        build(0,1,1,1);
        sort(v.begin(),v.end(),cmp);
        for(vector<node>::iterator it = v.begin();it < v.end(); it++)
        {
            printf("%d/%d\n",it->up,it->down);
        }
        printf("\n");
    }
}

抱歉!评论已关闭.