資料結構實驗之連結串列八:Farey序列

HowieLee59發表於2019-03-12

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;

typedef struct Node{
    int top;
    int bottom;
    struct Node *next;
}node;

void create(node * &head){
    node *p,*tail;
    head = new Node;
    head->next = NULL;
    tail = head;
    p = new Node;
    p->bottom = 1;
    p->top = 0;
    tail->next = p;
    tail = p;
    p = new Node;
    p->bottom = 1;
    p->top = 1;
    tail->next = p;
    tail = p;
}

void handle(node * &head,int n){
    node *p,*q,*k;
    int i;
    for(i = 2; i <= n ;i++){
        p = head->next;
        q = p->next;
        while(q){
            if((p->bottom + q->bottom) <= i){
                k = new Node;
                k->top = p->top + q->top;
                k->bottom = p->bottom + q->bottom;
                k->next = NULL;
                k->next = p->next;
                p->next = k;
            }
            p = q;
            q = q->next;
        }
    }
}
void printf(node * &head){
    node *cur;
    cur = head->next;
    int count = 0;
    while(cur){
        count++;
        if(count % 10 == 0){
            printf("%d/%d\n",cur->top,cur->bottom);
        }else{
            printf("%d/%d\t",cur->top,cur->bottom);
        }
        cur = cur->next;
    }
}

int main(){
    int n;
    node *head;
    scanf("%d",&n);
    create(head);
    if(n == 1){
        printf(head);
    }else{
        handle(head,n);
        printf(head);
    }
    return 0;
}

原本pe了一發,將空格改為\t之後奏效

相關文章