分治法
1.POJ3714
题目:
The system was charged by N nuclear power stations and breaking down any of them would disable the system.
The general soon started a raid to the stations by N special agents who were paradroped into the stronghold. Unfortunately they failed to land at the expected positions due to the attack by the Empire Air Force. As an experienced general, Arthur soon realized that he needed to rearrange the plan. The first thing he wants to know now is that which agent is the nearest to any power station. Could you, the chief officer, help the general to calculate the minimum distance between an agent and a station?
The first line is a integer T representing the number of test cases.
Each test case begins with an integer N (1 ≤ N ≤ 100000).
The next N lines describe the positions of the stations. Each line consists of two integers X (0 ≤ X ≤ 1000000000) and Y (0 ≤ Y ≤ 1000000000) indicating the positions of the station.
The next following N lines describe the positions of the agents. Each line consists of two integers X (0 ≤ X ≤ 1000000000) and Y (0 ≤ Y ≤ 1000000000) indicating the positions of the agent.
最近点对问题,注意是station与agent类间的最近点对。
算法描述:
需要定义⼀个Pointer的结构来存储station和agent的坐标(即x值与y值),还包含⼀个flag用来标记坐标是属于station还是agent。
- 先将输⼊的坐标数据按x排序,然后二分求解。
- 在合并子问题时,只需考虑横跨左右的答案。
- 取出所有与分界点x坐标之差不不超过左右子问题最⼩值ans的点,只有这些才是可能解。
- 将这些点按y排序。
- 对于每个点,只与和它y坐标之差不超过ans的点计算距离,直到找到最短的距离。
代码:
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <iomanip>
using namespace std;
const int N = 200000 + 1;
const double INF = 1e100;
struct Pointer{
double x,y;
bool flag;
};
Pointer m[N + 1];
int tmp[N + 1];
double dis(Pointer a,Pointer b){
return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));
}
bool cmpx(Pointer a,Pointer b){
return a.x < b.x;
}
bool cmpy(int a,int b){
return m[a].y < m[b].y;
}
double getMinLen(Pointer *s,int left,int right){
double rs = INF;
if (left == right)
return rs;
if (left + 1 == right) {
if (