一维最接近点对

#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int inf=0x3f3f3f3f;
double s[100];
double mn;
double min(double d1,double d2)
{
return d1>d2?d2:d1;
}
double closest(int low,int high)
{
if(low+1==high) return s[high]-s[low];
if(low+2==high) return min(s[high]-s[low+1],s[low+1]-s[low]);
int mid=(low+high)/2;
double ans=min(closest(low,mid),closest(mid+1,high));
if(s[mid+1]-s[mid]<ans) ans=s[mid+1]-s[mid];
return ans;
}
void sort(int *s,int *sn)
{
int n=sn-s,i,j,t;
for(i=0;i<n-1;i++)
for(j=0;j<=n-2-i;j++)
{
if(s[j]>s[j+1])
{
t=s[j];
s[j]=s[j+1];
s[j+1]=t;
}
}
}
int main(){
int n,m;
//随机生成种子值
srand(1);
while(~scanf("%d",&n)){

for(int i=0;i<n;i++){
s[i]=rand()%100;
printf("%lf ",s[i]);
}
printf(" ");
sort(s,s+n);
for(i=0;i<n;i++)
printf("%lf ",s[i]);
printf(" ");
printf("%.4lf ",closest(0,n-1));
}
}

原文地址:https://www.cnblogs.com/MarsMercury/p/8178816.html