数据结构实验之链表八:Farey序列
Time Limit: 10MS
Memory Limit: 600KB
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/4 4/5 5/6 1/1
Hint
#include
#include
struct node
{
int a, b;
struct node*next;
};
struct node*creat(int n)
{
struct node*head, *t, *p, *q, *tail;
head = (struct node*)malloc(sizeof(struct node));
p = (struct node*)malloc(sizeof(struct node));
p->a = 0;
p->b = 1;
head->next = p;
tail = p;
p = (struct node*)malloc(sizeof(struct node));
p->a = 1;
p->b = 1;
tail->next = p;
tail = p;
tail->next = NULL;
int m = n;
while(m--)
{
p = head->next;
q = p->next;
while(p->next&&q)
{
q = p->next;
// while(q)
// {
if(p->b + q->b <= n)
{
t = (struct node*)malloc(sizeof(struct node));
t->a = p->a + q->a;
t->b = p->b + q->b;
p->next = t;
t->next = q;
q = p->next;
}
else
{
p = p->next;
q = q->next;
}
//q = p->next;
//}
//p = p->next;
}
}
return (head);
};
void display(struct node*head)
{
struct node*p;
int n = 1;
p = head->next;
while(p->next)
{
if(n%10 == 0)
{
printf("%d/%d\n",p->a, p->b);
p = p->next;
n++;
}
else
{
printf("%d/%d\t",p->a, p->b);
p = p->next;
n++;
}
}
printf("%d/%d\n",p->a, p->b);
}
int main()
{
int n;
struct node*head;
scanf("%d",&n);
head = creat(n);
display(head);
return 0;
}