题解 | 小红的星屑共鸣
小红的星屑共鸣
https://www.nowcoder.com/practice/001cb736f02b4405819f3dad1cfc2382
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
typedef struct node
{
int x;
int y;
}Node;
int ComX(Node* node1, Node* node2)
{
if(node1->x > node2->x)
return 1;
else if(node1->x < node2->x)
return -1;
else
return 0;
}
long int getDist(Node node1, Node node2)
{
int disX = node1.x - node2.x;
int disY = node1.y - node2.y;
if((disX == 0) && (disY == 0))
return 0;
return (pow(disX, 2) + pow(disY, 2));
}
int main()
{
int n = 0;
int loop = 0;
scanf("%d", &n);
Node node[n];
for(loop = 0; loop < n; ++loop)
{
scanf("%d %d", &(node[loop].x), &(node[loop].y));
}
qsort(node, loop, sizeof(Node), ComX);
long int minDist = 0xffffffff;
long int curDist = 0;
for(loop = 0; loop < n; ++loop)
{
for(int j = loop+1; j < n; ++j)
{
if(minDist <= pow(node[loop].x - node[j].x, 2))
break;
curDist = getDist(node[loop], node[j]);
if(0 == curDist)
{
printf("0");
return 0;
}
else if(minDist > curDist)
minDist = curDist;
}
}
printf("%ld", minDist);
return 0;
}