数据结构实验之链表八:Farey序列
Time Limit: 10 ms Memory Limit: 600 KiB
Submit Statistic Discuss
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个分数,同一行的两个相邻分数间隔一个制表符的距离。
Sample Input
6
Sample Output
0/1 1/6 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4
4/5 5/6 1/1
Hint
Source
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LISTSIZE 10000
#define LISTINCREASEMENT 100
struct node
{
int edata,sdata;
struct node *next;
};
int main()
{
int n;
scanf("%d",&n);
struct node*head,*tail,*p;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
for(int i=1; i<=2; i++)
{
p=(struct node*)malloc(sizeof(struct node));
p->next=NULL;
if(i==1)
{
p->sdata=0;
p->edata=1;
}
else
{
p->sdata=1;
p->edata=1;
}
tail->next=p;
tail=p;
}
int s=0;
if(n==1)
{
p=head->next;
while(p)
{
s++;
if(s%10==0)
{
printf("%d/%d\n",p->sdata,p->edata);
}
else printf("%d/%d\t",p->sdata,p->edata);
p=p->next;
}
printf("\n");
}
else
{
for(int i=1; i<=n-1; i++)
{
p=head->next;
while(p->next!=NULL)
{
if(p->edata+p->next->edata<=n)
{
struct node*q;
q=(struct node*)malloc(sizeof(struct node));
q->sdata=p->sdata+p->next->sdata;
q->edata=p->edata+p->next->edata;
q->next=NULL;
q->next=p->next;
p->next=q;
p=p->next->next;
}
else p=p->next;
}
}
s=0;
p=head->next;
while(p)
{
s++;
if(s%10==0)
{
printf("%d/%d\n",p->sdata,p->edata);
}
else printf("%d/%d\t",p->sdata,p->edata);
p=p->next;
}
printf("\n");
}
return 0;
}
版权声明:本文为BHliuhan原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。