13. 两个有序序列的中位数(25)(ZJU

题目链接:

已知有两个等长的非降序序列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 64

26-100 -10 1 1 1 1-50 0 2 3 4 51

331 2 34 5 63

434 5 61 2 33

51211

PS:

这题说多了都是泪,怪自己智商捉急,看见题目里的并集,就煞笔的去了重,然后……然后最后一个案例WA到吐都过不了!用了各种方法…………

代码一如下(链表):

#include <cstdio>#include <cstring>#include <malloc.h>#define LEN sizeof(struct node)struct node{int x;struct node *next;};int N;struct node *creat(){struct node *p1, *p2, *head1;p1=p2=head1=(struct node*)malloc(LEN);int t = N;head1 = NULL;int n = 0;while(t–){p1 = (struct node *)malloc(LEN);scanf("%d",&p1->x);n++;if(n == 1)head1 = p1;elsep2->next = p1;p2 = p1;}p2->next = NULL;return head1;}struct node *findd(struct node *p1, struct node *p2){struct node *p3;p3 = NULL;if(p1 == NULL)return p2;if(p2 == NULL)return p1;if(p1->x < p2->x){p3 = p1;p3->next = findd(p1->next,p2);}else if(p1->x == p2->x){p3 = p1;p3->next = findd(p1->next,p2);}else{p3 = p2;p3->next = findd(p1,p2->next);}return p3;}void print(struct node *head){struct node *p;p = head;int n = 0;while(p!=NULL){if(n == (2*N-1)/2){printf("%d\n",p->x);break;}p = p->next;n++;}}int main(){scanf("%d",&N);struct node *p, *head1, *head2;head1 = creat();head2 = creat();p = findd(head1, head2);print(p);return 0;}代码二如下(数组):#include <cstdio>#include <cstring>const int maxn = 100017;int a[maxn], b[maxn], c[maxn];int main(){int n;while(~scanf("%d",&n)){for(int i = 0; i < n; i++){scanf("%d",&a[i]);}for(int i = 0; i < n; i++){scanf("%d",&b[i]);}int l = 0;int i = 0, j = 0;while(i < n && j < n){if(a[i] == b[j]){c[l++] = a[i];c[l++] = b[j];//这一行开始没加WA到吐i++,j++;}if(a[i] < b[j]){c[l++] = a[i];i++;}else{c[l++] = b[j];j++;}}while(i < n){c[l++] = a[i];i++;}while(j < n){c[l++] = b[j];j++;}printf("%d\n",c[(l-1)/2]);}return 0;}

到尽头,也许快乐,或有时孤独,如果心在远方,

13. 两个有序序列的中位数(25)(ZJU

相关文章:

你感兴趣的文章:

标签云: