您的位置:首页 > 理论基础 > 数据结构算法

PAT《数据结构学习与实验指导》实验项目集 2-13

2015-08-15 12:03 411 查看
已知有两个等长的非降序序列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
1 3 5 7 9
2 3 4 5 6

4

2
6
-100 -10 1 1 1 1
-50 0 2 3 4 5

1

3
3
1 2 3
4 5 6

3

4
34 5 6
1 2 3

3

5
12
1

1

合并列表的改进版,只要计一下数就可以了。

#include<iostream>
#include<list>
using namespace std;
int main(){
list<int> list1;
list<int> list2;
int n,m;
cin>>n;
for(int i=0;i<n;i++){
cin>>m;
list1.push_back(m);
}
for(int j = 0;j<n;j++){
cin>>m;
list2.push_back(m);
}
int count=0;
list<int>::iterator iter1 = list1.begin();
list<int>::iterator iter2 = list2.begin();
while(iter1 != list1.end() && iter2 != list2.end()){
if(*iter1 < *iter2){
if(count == n-1){
cout<<*iter1<<endl;
break;
}
iter1++;
count++;
}else{
if(count == n-1){
cout<<*iter2<<endl;
break;
}
iter2++;
count++;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: