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

来源:互联网 发布:复活吧我的勇士java 编辑:程序博客网 时间:2024/06/02 17:07

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

Time Limit: 10MS Memory Limit: 600K  

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
#include<stdio.h>#include<algorithm>#include<iostream>#include<string.h>#include<stdlib.h>#include<queue>#include<vector>#include<math.h>using namespace std;const int MAX = 1000+10;struct node{    int a, b;    struct node *next;};/*struct node *creat(int n){    struct node *p,*head;    p=new node;    head=p;    head->next=NULL;    for (int i=1; i<=n; i++)    {        p=new node;        scanf("%d",&p->data);        p->next=head->next;        head->next = p;    }    return head;}*//*void show(node *head){node *p = head->next;while(p->next!=NULL){printf("%d ", p->data);p = p->next;}printf("%d\n", p->data);}*/node *unfold(){node *p;p = new node;p->next = NULL;return p;}node *unfold2(){node *p, *q, *r;p = unfold();q = unfold();r = unfold();q->a = 0;q->b = r->a = r->b = 1;p->next = q;q->next = r;return p;}node *creat2(node *head1, int n){node *head2, *p, *q, *t;head2 = unfold();p = head1->next;q = head2;while(p){q->next = p;p = p->next;q = q->next;if(p&&q&&p->b+q->b<=n){t = unfold();t->a = p->a+q->a;t->b = p->b+q->b;q->next = t;q = q->next;}}return head2;}void show2(node *head){node *p = head->next;int cnt = 0;while(p){++cnt;if(cnt%10){printf("%d/%d\t", p->a, p->b);}else printf("%d/%d\n", p->a, p->b);p = p->next;}}int main(){    int n;    scanf("%d",&n);    struct node * head;    head=unfold2();for(int i = 1; i<n; ++i){head = creat2(head, n);}show2(head);    return 0;}

0 0
原创粉丝点击