已经调了 1 h,貌似是 sort 的问题?
#include <bits/stdc++.h>
using namespace std;
const int maxn=4*1e5+5;
struct node
{
int x,y;
friend bool operator < (node a1,node a2)
{
if(a1.x==a2.x) return a1.y<a2.y;
return a1.x<a2.x;
}
}dot[maxn];
int q[maxn];
bool cmp(node a,node b)
{
return a.y<b.y;
}
int dis(int a,int b)//计算两点间距离
{
return (dot[a].x-dot[b].x)*(dot[a].x-dot[b].x)+(dot[a].y-dot[b].y)*(dot[a].y-dot[b].y);
}
int work(int l,int r)
{
if(l==r) return 1ll<<31;
if(l==r-1) return dis(l,r);
int mid=(l+r)/2;
int d;
d=min(work(l,mid),work(mid+1,r));
int tot=0;//记录q集合中的总点数
for(int i=1;i<=r;i++)
if(abs(dot[mid].x-dot[i].x)<d) q[++tot]=i;//q存储编号
sort(q,q+tot+1,cmp);
for(int i=1;i<=tot;i++)
for(int j=i+1;j<=tot&&dot[q[i]].y-dot[q[j]].y<d;j++)
d=min(d,dis(q[i],q[j]));
return d;
}
signed main()
{
int n;cin>>n;
for(int i=1;i<=n;i++) cin>>dot[i].x>>dot[i].y;
std::sort(dot+1,dot+n+1);
cout<<work(1,n);
return 0;
}