7-1 两个有序序列的中位数 (20 分)
时间限制: 200 ms 内存限制: 64 MB 代码长度限制: 16 KB
已知有两个等长的非降序序列S1, S2, 设计函数求S1与S2并集的中位数。有序序列A0,A1,⋯,AN−1的中位数指A(N−1)/2的值,即第⌊(N+1)/2⌋个数(A0为第1个数)。
输入格式:
输入分三行。第一行给出序列的公共长度N(0<N≤100000),随后每行输入一个序列的信息,即N个非降序排列的整数。数字用空格间隔。
输出格式:
在一行中输出两个输入序列的并集序列的中位数。
输入样例1:
5
1 3 5 7 9
2 3 4 5 6
输出样例1:
4
输入样例2:
6
-100 -10 1 1 1 1
-50 0 2 3 4 5
输出样例2:
1
#include<stdio.h>
typedef struct node *ptrNode;
typedef ptrNode LinkList; //頭結點
typedef ptrNode Position;//中間節點
typedef int ElementType;
struct node{
ElementType Element;
Position next;
};
LinkList creatList(int n)
{
LinkList head,r,p;
int x,i;
head = (struct node*)malloc(sizeof(struct node)); //生成新結點
r = head;
for(i = 0; i < n; i++){
scanf("%d",&x);
p = (struct node*)malloc(sizeof(struct node));
p->Element = x;
r->next = p;
r = p;
}
r->next = NULL;
return head;
}
LinkList mergeList(LinkList a, LinkList b)
{
Position ha, hb,hc;
LinkList c,r,p;
ha = a->next;
hb = b->next;
c = (struct node*)malloc(sizeof(struct node));
r = c;
while((ha != NULL)&&(hb != NULL)){
p = (struct node*)malloc(sizeof(struct node));
if(ha->Element <= hb->Element){
p->Element = ha->Element;
ha = ha->next;
}
else{
p->Element = hb->Element;
hb = hb->next;
}
r->next = p;
r = p;
}
if(ha == NULL){
while(hb != NULL){
p = (struct node*)malloc(sizeof(struct node));
p->Element = hb->Element;
hb = hb->next;
r->next = p;
r = p;
}
}
if(hb == NULL){
while(ha != NULL){
p = (struct node*)malloc(sizeof(struct node));
p->Element = ha->Element;
ha = ha->next;
r->next = p;
r = p;
}
}
r->next = NULL;
return c;
}
int medianOfLinklist(LinkList L, int n)
{
LinkList ha;
int i;
ha = L;
for(i = 0; i <= (n-1)/2;i++){
ha = ha->next;
}
return ha->Element;
}
int main(void)
{
LinkList L1,L2,L3;
int n,median;
scanf("%d",&n);
L1 = creatList(n);
L2 = creatList(n);
L3 = mergeList(L1,L2);
median = medianOfLinklist(L3, 2*n);
printf("%2d",median);
return 0;
}