POJ - 3714 Raid【分治】【二分】
【题目描述】
After successive failures in the battles against the Union, the Empire retreated to its last stronghold. Depending on its powerful defense system, the Empire repelled the six waves of Union’s attack. After several sleepless nights of thinking, Arthur, General of the Union, noticed that the only weakness of the defense system was its energy supply. 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.
【输出】
For each test case output the minimum distance with precision of three decimal placed in a separate line.
【样例输入】
2
4
0 0
0 1
1 0
1 1
2 2
2 3
3 2
3 3
4
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
【样例输出】
1.414
0.000
题目链接:https://vjudge.net/problem/POJ-3714
平面最近点对问题
代码如下:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
using namespace std;
#define int long long
static const int INF=0x3f3f3f3f3f3f3f3f;
static const int MAXN=1000000;
struct Node{
int x,y,z;
}a[MAXN*2+10],b[MAXN*2+10];
int T,n;
bool cmp1(Node a,Node b) {
if(a.x==b.x)
return a.y<b.y;
return a.x<b.x;
}
bool cmp2(Node a,Node b) {
if(a.y==b.y)
return a.x<b.x;
return a.y<b.y;
}
double dist(Node p,Node q) {
if(p.z==q.z) return INF;
return sqrt((p.x-q.x)*(p.x-q.x)+(p.y-q.y)*(p.y-q.y));
}
double solve(int l,int r)
{
int mid=(l+r)>>1;
if(r==l)
return INF;
if(r-l==1)
return dist(a[l],a[r]);
double ans=min(solve(l,mid),solve(mid+1,r));
int t=0;
for(int i=l;i<=r;i++)
if(a[mid].x-ans<=a[i].x && a[i].x<=a[mid].x+ans)
b[++t]=a[i];
sort(b+1,b+t+1,cmp2);
for(int i=1;i<=t;i++)
for(int j=i+1;j<=t;j++)
{
if(b[j].y>=b[i].y+ans)
break;
ans=min(ans,dist(b[i],b[j]));
}
return ans;
}
signed main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0),cout.tie(0);
cin>>T;
while(T--)
{
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i].x>>a[i].y;
a[i].z=1;
}
for(int i=1;i<=n;i++)
{
cin>>a[i+n].x>>a[i+n].y;
a[i+n].z=2;
}
sort(a+1,a+n*2+1,cmp1);
cout<<fixed<<setprecision(3)<<solve(1,2*n)<<endl;
}
return 0;
}
上一篇: poj3714 Raid (分治)