数据结构实验之链表八:Farey序列

来源:互联网 发布:程序员推荐用什么键盘 编辑:程序博客网 时间:2024/06/07 23:12

数据结构实验之链表八:Farey序列

Time Limit: 10MS Memory Limit: 600KB
Submit Statistic

Problem Description

Farey序列是一个这样的序列:其第一级序列定义为(0/1,1/1),这一序列扩展到第二级形成序列(0/1,1/2,1/1),扩展到第三极形成序列(0/1,1/3,1/2,2/3,1/1),扩展到第四级则形成序列(0/1,1/4,1/3,1/2,2/3,3/4,1/1)。以后在每一级n,如果上一级的任何两个相邻分数a/c与b/d满足(c+d)<=n,就将一个新的分数(a+b)/(c+d)插入在两个分数之间。对于给定的n值,依次输出其第n级序列所包含的每一个分数。

Input

输入一个整数n(0<n<=100)

Output

依次输出第n级序列所包含的每一个分数,每行输出10个分数,同一行的两个相邻分数间隔一个制表符的距离。

Example Input

6

Example Output

0/1   1/6   1/5   1/4   1/3   2/5   1/2   3/5   2/3   3/44/5   5/6   1/1
本题的算法不得不说十分奇妙,借了一下别人的思路,要生成n的farey序列,就从1到n的序列依次生成就OK;
#include<stdio.h>#include<stdlib.h>typedef struct node{    int a, b;    struct node *next;}*linkList;void creatList(linkList &L,int n){           //依次建立farey序列    linkList p, q, tail;    tail = L->next;    while(tail->next){    p = tail->next;    if(p->b + tail->b <= n){            //增加一个新的分数的条件    q = new node;    q->a = p->a + tail->a;      //新的分数与相邻元素的关系    q->b = p->b + tail->b;    tail->next = q;    q->next = p;    }    tail = tail->next;    }};void outputData(linkList &L){              //输出序列linkList p;      p = L->next;      int cnt = 0;      while(p){          cnt++;          if(!(cnt%10))              printf("%d/%d\n",p->a,p->b);          else              printf("%d/%d\t",p->a,p->b);          p = p->next;      }  }int main(){    int n;    scanf("%d", &n);    linkList L, p, q;    L = new node;    L->next = NULL;    p = new node, q = new node;    p->a = 0, p->b = 1;                   //初始的n为1是的两个分数    q->a = 1, q->b = 1;    L->next = p;    p->next = q;    q->next = NULL;    for(int i = 2; i <= n; i++)           //循环依次建立序列    creatList(L, n);    outputData(L);    return 0;}


原创粉丝点击