数据结构实验之链表八:Farey序列
Time Limit: 10 ms Memory Limit: 600 KiB
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
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct node
{
int a;
int b;
node *next;
};
void initnode(node *p,int a,int b)
{
p->a = a;
p->b = b;
}
int main()
{
int n;
cin>>n;
node *head = new node;
head->next = NULL;
node *tail = new node;
tail ->next = NULL;
tail = head;
node *p = new node;
p->next = NULL;
initnode(p,0,1);
tail ->next = p;
tail = p;
node *q = new node;
q->next = NULL;
initnode(q,1,1);
tail ->next = q;
tail = q;
// for(tail = head->next;tail != NULL; tail = tail->next)
// {
// cout<<tail->a<<"/"<<tail->b<<" ";
// }
node *t = new node;
node *r = new node;
int flag = 1;
while(flag)
{
flag = 0;
for(t = head->next,r = t->next; r!=NULL;t = t->next,r = r->next)
{
if(t->b + r->b <= n)
{
node *g = new node;
g->next = NULL;
g->a = t->a + r->a;
g->b = t->b + r->b;
g->next = r;
t->next = g;
t = t->next;
flag = 1;
}
}
}
int c = 1;
for(node * tail = head->next;tail!=NULL;tail = tail->next,c ++)
{
cout<<tail->a<<"/"<<tail->b;
if(c%10==0&&c!=0)
{
cout<<endl;
}else
{
cout<<"\t";
}
}
return 0;
}