邮局问题 快速排序 分治

 
  
 
  
// 邮局选址问题.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
#include 
#include 
#include 
#include 
#include 
using std::cin;
using std::cout;
using std::vector;
using std::endl;
using std::sort;
using std::shared_ptr;
using std::make_shared;
using std::ifstream;
using std::string;

class Solution 
{
public:
	void QuickSort(vector &v, int low, int high) 
	{
		if (low < high) //递归跳出条件
		{
			int pivotpos = Partition(v,low,high);
			QuickSort(v, low, pivotpos - 1);
			QuickSort(v, pivotpos + 1, high);
		}
	}
	int Partition(vector &v, int low, int high) 
	{
		int pivot = v[low];//设置为枢轴值
		while (low < high) 
		{
			while (low < high&&v[high] >= pivot)--high;
			v[low] = v[high];//比基准值小的移动到左边
			while (low < high&&v[low] <= pivot)++low;
			v[high] = v[low];//比基准值大的移动到右边
		}
		v[low] = pivot;
		return low;
	}
	int mid(vector v) //找中位数
	{
		return v[v.size()/2];
	}
};
int main() 
{
	for (int i = 0; i < 5; i++) 
	{
		cout << "第"< vx;//保存居民点的x坐标
		vector vy;//居民点的y坐标
		ifstream infile;
		//infile.open("input_assign01_01.dat");
		infile.open(s);
		if (!infile) cout << "error" << endl;
		int t1;
		//存入vector
		//cout<<"存入vector"< ve;
		int count = 0;
		while (infile >> t1)             //按空格读取,遇到空白符结束
		{
			if (count == 0) //存一个x坐标
			{
				vx.push_back(t1);
				count = 1;
			}
			else //存一个y坐标
			{
				vy.push_back(t1);
				count = 0;
			}

		}
		infile.close();//文件关闭
		cout << "居民点坐标:";
		for (int i = 0; i < vx.size(); i++)
		{
			cout << "(" << vx[i] << "," << vy[i] << ")";
		}
		cout << endl;
		int mid_x, mid_y;
		//给x y单独排序 找中位数
		shared_ptr q = make_shared();
		q->QuickSort(vx, 0, vx.size() - 1);
		q->QuickSort(vy, 0, vy.size() - 1);
		
		
		mid_x = q->mid(vx);
		mid_y = q->mid(vy);
		cout << "邮局坐标:" << mid_x << " " << mid_y << endl;
		
	}
	system("pause");
}
在一个按照东西和南北方向划分成规整街区的城市里,n个居民点散乱地分布在不同的街区中。用x坐标表示东西向,用y坐标表示南北向。各居民点的位置可以由坐标(x,y)表示。要求:为建邮局选址,使得n个居民点到邮局之距离的总和最小。
运行环境 VS2015
运行过程 每个输入文件都是一堆数字 奇数项是x坐标 偶数是y坐标 把输入文件和代码或可执行文件放置一个文件夹里面就可以执行
算法设计
这道题和poj上面的一道题十分相似 我们可以将x 和y看成独立的问题去求解 分别求x坐标集合和y坐标集合的中位数 然后合起来作为最后答案
读入x和y坐标 采用基于分治法的快速排序将其排好队 然后求中位数 在等待排序的集合中找一个基准 将其分成两部分 小于基准的 和大于等于的

基准的位置固定 递归划分子序列

邮局问题 快速排序 分治_第1张图片

你可能感兴趣的:(算法,分治)