PAT 2-13 两个有序序列的中位数(C语言实现)
来源:互联网 发布:阿尔及利亚地图软件 编辑:程序博客网 时间:2024/05/17 03:51
题目描述:
已知有两个等长的非降序序列S1, S2, 设计函数求S1与S2并集的中位数。有序序列A0, A1…AN-1的中位数指A(N-1)/2的值,即第[(N+1)/2]个数(A0为第1个数)。
输入格式说明:
输入分3行。第1行给出序列的公共长度N(0<N<=100000),随后每行输入一个序列的信息,即N个非降序排列的整数。数字用空格间隔。
输出格式说明:
在一行中输出两个输入序列的并集序列的中位数。
样例输入与输出:
序号输入输出151 3 5 7 92 3 4 5 6
42
6-100 -10 1 1 1 1-50 0 2 3 4 5
13
31 2 34 5 6
34
34 5 61 2 3
35
121
1
解答说明:
利用两个序列都是非降序排列的特性,现将两个序列合并,再取第(N-1)/2个数即可。可调用前面对两个链表进行合并所写的函数。
源码:
#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("%d",median);return 0;}
0 0
- PAT 2-13 两个有序序列的中位数(C语言实现)
- PAT DS 2-13两个有序序列的中位数
- PAT 2-11 两个有序链表序列的合并(C语言实现)
- PAT 2-12 两个有序链表序列的交集(C语言实现)
- pat 两个有序序列的中位数
- PAT 两个有序序列的中位数
- 【C】两个有序序列的中位数
- 浙大PAT 2-13. 两个有序序列的中位数 (解题思路)
- 两个有序序列的中位数(详解)
- 实验项目2-13:两个有序序列的中位数
- 2-13. 两个有序序列的中位数(25)
- 2-13. 两个有序序列的中位数(25)
- 两个有序序列的中位数
- 两个有序序列的中位数
- 浙江大学PAT上机题解析之2-13. 两个有序序列的中位数
- PAT1019. 两个有序序列的中位数(25)
- 两个有序序列的中位数(25 分)
- 两个有序序列的中位数(25 分)
- Java设计模式菜鸟系列(二)观察者模式建模与实现
- easyUI中combobox的使用心得
- LeetCode: Recover Binary Search Tree
- 第六届省赛 E Internal Rate of Return(UVA 11881)二分求根
- NYOJ 298 点的变换(矩阵快速幂)
- PAT 2-13 两个有序序列的中位数(C语言实现)
- Zoj 3535 Gao the String II (AC自动机+dp)
- MapReduce 编程 系列十 使用HashPartitioner来调节Reducer的计算负载
- 复分析中的欧拉恒等式
- 【人脸识别】人脸识别必读论文
- ACdream Andrew Stankevich's Contest (2) 哈夫曼树
- 三分钟学会刻录光盘
- 在odl中如何实现rpc
- Selenium Webdriver java 积累一