JOBDU Q1004

来源:互联网 发布:python爬虫 pdf 编辑:程序博客网 时间:2024/06/10 03:45

题目:有序数列合并,输出中位数

/*题目描述:Given an increasing sequence S of N integers, the median is the number at the middle position. For example, the median of S1={11, 12, 13, 14} is 12, and the median of S2={9, 10, 15, 16, 17} is 15. The median of two sequences is defined to be the median of the non-decreasing sequence which contains all the elements of both sequences. For example, the median of S1 and S2 is 13.Given two increasing sequences of integers, you are asked to find their median.输入:Each input file may contain more than one test case.Each case occupies 2 lines, each gives the information of a sequence. For each sequence, the first positive integer N (≤1000000) is the size of that sequence. Then N integers follow, separated by a space.It is guaranteed that all the integers are in the range of long int.输出:For each test case you should output the median of the two given sequences in a line.样例输入:4 11 12 13 145 9 10 15 16 17样例输出:13*/#include <iostream>using namespace std;//定义链表节点class node{public:long v;node * next;};//在有序链表L中插入一个节点,并仍保证其有序void insert(node * i, node * L){node * a = new node;a = L;for (;;){if (a->next == NULL)//走到链表末端,在最后插入{a->next = i;break ;}else if (i->v < a->next->v)//未到尾,满足插入条件,插入{i->next = a->next;a->next = i;break ;}else a = a->next;//未到尾,不满足插入条件,向后走}return;}int main(){long n1, n2;long i;while (cin >> n1){//创建链表a(的头结点)node * a = new node;a->next = NULL;node * x = new node;x = a;//得到包含(n1 + 1)个节点的有序链表afor (i = 0; i < n1; i++){node * n = new node;n->next = NULL;cin >> n->v;while (x->next) x = x->next;x->next = n;x = x->next;}cin >> n2;//向a中插入另外n2个节点,并保证其有序for (i = 0; i < n2; i++){node * n = new node;n->next = NULL;cin >> n->v;insert(n, a);}//有序链表a包含头结点共有(n1 + n2 + 1)个元素//计算其中位数并输出x = a->next;for (i = 0; i < (n1 + n2 - 1)/2; i++){x = x->next;}cout << x->v << endl;}return 0;}


注意:

1)数据量太大,数组结构不能满足题目要求;

2)创建新节点:

node * a = new node;a->next = NULL;

3)计算中位数是需要格外注意条件的控制:考虑头结点、 < 或 <= 等问题。


0 0