主题链接:http://pat.zju.edu.cn/contests/ds/2-13
已知有两个等长的非降序序列S1, S2, 设计函数求S1与S2并集的中位数。有序序列A0, A1…AN-1的中位数指A(N-1)/2的值,即第[(N+1)/2]个数(A0为第1个数)。
输入格式说明:
输入分3行。第1行给出序列的公共长度N(0<N<=100000),随后每行输入一个序列的信息。即N个非降序排列的整数。数字用空格间隔。
输出格式说明:
在一行中输出两个输入序列的并集序列的中位数。
例子输入与输出:
序号 | 输入 | 输出 |
1 |
5 |
4 |
2 |
6 |
1 |
3 |
3 |
3 |
4 |
3 |
3 |
5 |
1 |
1 |
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMjg2MDA2Mw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
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;
else
p2->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;
}
版权声明:本文博主原创文章,博客,未经同意不得转载。