分治法习题整理

分治法

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。

  1. 先将输⼊的坐标数据按x排序,然后二分求解。
  2. 在合并子问题时,只需考虑横跨左右的答案。
  3. 取出所有与分界点x坐标之差不不超过左右子问题最⼩值ans的点,只有这些才是可能解。
  4. 将这些点按y排序。
  5. 对于每个点,只与和它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 (s[left].flag == s[right].flag)
            return rs;
        r
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值