JOBDU Q1004

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

/*
题目描述:
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 14
5 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)个节点的有序链表a
		for (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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值