Raid
Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 18435 | Accepted: 4992 |
Description
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?
Input
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.
Output
For each test case output the minimum distance with precision of three decimal placed in a separate line.
Sample Input
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
Sample Output
1.414
0.000
思想:采用分治的算法。Accepted
#include<iostream>
#include<cstring>
#include<algorithm>
#include<math.h>
#include<stdio.h>
using namespace std;
const int maxn=200020;
const double far=1e10;
struct point{
double x, y;
int mark;
};
double dis(point a, point b){
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
bool cmpx(point a,point b){
return a.x<b.x;
}
double mini(double x, double y){
if((x - y)>0.0)
return y;
else
return x;
}
point p[maxn];
double findmin(int l, int r,int n){
if(l>=r){
return far;
}
if(r==l+1){
if(p[l].mark==p[r].mark){
return far;
}else{
return dis(p[l], p[r]);
}
}
int mid=(l+r)/2;
double d1=findmin(l, mid, n);
double d2=findmin(mid+1, r, n);
double d=mini(d1,d2);
for(int i=l; i<=r; i++){
if(p[i].mark!=p[mid].mark)
d=min(d, dis(p[mid], p[i]));
}
return d;
}
int main(){
int T;
double x, y;
scanf("%d", &T);
while(T--){
int n;
scanf("%d", &n);
for(int i=0;i<n;i++){
scanf("%lf%lf",&x,&y);
p[i]=(point){x,y,0};
}
for(int i=n;i<n+n;i++){
scanf("%lf%lf",&x,&y);
p[i]=(point){x,y,1};
}
sort(p,p+2*n,cmpx);
double kk=findmin(0,2*n-1,2*n);
printf("%.3f\n",kk);
}
return 0;
}