Nearest Neighbor Search

          ## Nearest Neighbor Search ##

Input file: standard input
Output file: standard output
Time limit: 1 second
Memory limit: 1024 megabytes
Bobo has a point p and a cube C in 3-dimension space. The point locates at coordinate (x0, y0, z0), while
C = {(x, y, z) : x1 ≤ x ≤ x2, y1 ≤ y ≤ y2, z1 ≤ z ≤ z2}.
Bobo would like to find another point q which locates inside or on the surface of the cube C so that the
square distance between point p and q is minimized.
Note that the square distance between point (x, y, z) and (x′, y′, z′) is (x − x′)2 + (y − y′)2 + (z −z′)2.
Input
The first line contains 3 integers x0, y0, z0.
The second line contains 3 integers x1, y1, z1.
The third line contains 3 integers x2, y2, z2.
(|xi|, |yi|, |zi| ≤ 104, x1 < x2, y1 < y2, z1 < z2)
Output
An integer denotes the minimum square distance.
Examples
standard input standard output
0 0 0
1 1 1
2 2 2
3
1 1 1
0 0 0
2 2 2
0

题目连接:https://acm.bnu.edu.cn/v3/statments/52296.pdf

真的是水到不能再水的题,虽然比赛的时候没做出来。。。,q点的x,y,z坐标可以独立求,每次都求最小值,如果点q在cube C之中的话,距离肯定是0,问题就是判断在cube C的外面的情况,这种情况下求到两端范围内的最小值就行了。

#include<queue>
#include<stack>
#include<vector>
#include<math.h>
#include<stdio.h>
#include<numeric>//STL数值算法头文件
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<functional>//模板类头文件
using namespace std;

const int INF=1e9+7;
const int maxn=101000;

struct Node
{
    int x,y,z;
};
long long getans(Node a,Node b)
{
    return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)+(a.z-b.z)*(a.z-b.z);
}

int main()
{
    Node a,b,c;
    while(scanf("%d%d%d%d%d%d%d%d%d",&a.x,&a.y,&a.z,&b.x,&b.y,&b.z,&c.x,&c.y,&c.z)!=EOF)
    {
        Node t;
        if((a.x>=b.x&&a.x<=c.x)||(a.x<=b.x&&a.x>=c.x)) t.x=a.x;
        else t.x=(abs(a.x-b.x)>abs(a.x-c.x))?c.x:b.x;

        if((a.y>=b.y&&a.y<=c.y)||(a.y<=b.y&&a.y>=c.y)) t.y=a.y;
        else t.y=(abs(a.y-b.y)>abs(a.y-c.y))?c.y:b.y;

        if((a.z>=b.z&&a.z<=c.z)||(a.z<=b.z&&a.z>=c.z)) t.z=a.z;
        else t.z=(abs(a.z-b.z)>abs(a.z-c.z))?c.z:b.z;

        printf("%lld\n",getans(a,t));
    }
}
posted @ 2017-03-15 22:02  xushukui  阅读(175)  评论(0编辑  收藏  举报