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
5 1 2 2 3 5 5 1 0 2 1 3 1 7 2
Example Output
0 1 2 2 3 5 0 1 2 2 3 3 5 7
code:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *creat(int n)
{
struct node *head, *p, *tail;
int i;
head = (struct node*)malloc(sizeof(struct node));
tail = head;
head->next = NULL;
for(i = 0; i<n; i++)
{
p = (struct node*)malloc(sizeof(struct node));
scanf("%d", &p->data);
tail->next = p;
p->next = NULL;
tail = p;
}
return (head);
}
void sert(struct node *head)
{
struct node *p, *q, *t;
int flag = 1;
p = head;
q = head->next;
t = (struct node*)malloc(sizeof(struct node));
scanf("%d", &t->data);
while(q)
{
if(q->data>t->data)
{
flag = 0;
p->next = t;
t->next = q;
break;
}
else
{
p = p->next;
q = q->next;
}
}
if(flag)
{
p->next = t;
t->next = NULL;
}
}
void show(struct node *head)
{
struct node *r = head->next;
while(r)
{
if(r->next==NULL) printf("%d\n", r->data);
else printf("%d ", r->data);
r = r->next;
}
}
int main()
{
int n, x, t, i;
struct node *head, *p, *q;
while(~scanf("%d", &n))
{
head = creat(n);
scanf("%d", &t);
for(i = 0; i<t; i++)
{
scanf("%d", &x);
if(x==1) sert(head);
else if(x==2) show(head);
}
p = head->next;
while(p)
{
q = p->next;
free(p);
p = q;
}//多组输入需释放掉前一组占用的内存,否则Memory Limit Exceeded
}
return 0;
}