插入排序

来源:互联网 发布:python 包 编辑:程序博客网 时间:2024/06/03 05:49

插入排序

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic

Problem Description

现有 n 个从小到大排列的数组成的序列。需要对这个序列进行 c 次操作。

每次操作有两种类型:

  • 操作 1:插入一个数 v 到序列中,并保持有序。
  • 操作 2:输出当前的序列。

bLue 并不太擅长序列操作,所以他想来请求你的帮助,你能帮助他完成这个任务吗?

Input

输入数据有多组(数据组数不超过 30),到 EOF 结束。

对于每组数据:

  • 第 1 行输入一个整数 n (1 <= n <= 10^5),表示初始的有序序列中数字的个数。
  • 第 2 行输入 n 个用空格隔开的整数 ai (0 <= ai <= 10^6),表示初始序列。
  • 第 3 行输入一个整数 c (1 <= c <= 1000),表示有 c 次操作。
  • 接下来有 c 行,每行表示一次操作:
    • 如果操作类型为 1,则输入格式为 "1 v",其中 v (0 <= v <= 1000) 表示要插入到序列的数。
    • 如果操作类型为 2,则输入格式为 "2"。

Output

对于每组数据中的每次类型为 2 的操作,输出一行,表示当前的序列,每个数之间用空格隔开。

Example Input

51 2 2 3 551 021 31 72

Example Output

0 1 2 2 3 50 1 2 2 3 3 5 7
此题注意在输入另一组新的数据的时候要释放掉内存,否则会出现超内存的情况。
#include <stdio.h>#include <stdlib.h>struct node{    int data;    struct node *next;};struct node *chaifen(struct node *head);struct node *creat(int n);void put(struct node *head);void join(struct node *head);int main(){    int n, m, t;    struct node *head, *p, *q;    while(~scanf("%d",&n))    {        head=creat(n);        scanf("%d", &t);        while(t--)        {            scanf("%d", &m);            if(m == 1)                join(head);            else if(m == 2)                put(head);        }        p=head->next;         while(p)         {             q=p->next;             free(p);             p=q;         }    }    return 0;}struct node *creat(int n){    int i;    struct node *head,*p, *tail;    head=(struct node *)malloc(sizeof(struct node));    head->next=NULL;    tail = head;    for(i=0; i<n; i++)    {        p=(struct node *)malloc(sizeof(struct node));        scanf("%d",&p->data);        p->next = NULL;        tail->next = p;        tail = p;    }    return head;};void put(struct node *head){    struct node *p;    p = head->next;    while(p)    {        if(p->next!=NULL)            printf("%d ",p->data);        else            printf("%d\n",p->data);        p=p->next;    }}void join(struct node *head){    struct node *p, *q, *r;    p = head->next;    r = head;    q = (struct node*)malloc(sizeof(struct node));    scanf("%d", &q->data);    while(p)    {        if(p->data > q->data)        {            q->next = p;            r->next = q;            break;        }        else        {            r = p;            p = p->next;        }    }    if(p == NULL)    {        q->next = p;        r->next = q;    }}

0 0