closest

import math
import random
import matplotlib.pyplot as plt
import time
limitx=300000
limity=300000
threshold=2
data=[]
datax=[]
datay=[]
datanum=20000
for i in range(datanum):
    point=[]
    x=random.random()*limitx
    y=random.random()*limity
    point.append(x)
    point.append(y)
    datax.append(x)
    datay.append(y)
    data.append(point)
#print(data)
plt.scatter(datax,datay,c='black')
plt.show()
a=-1
b=-1
minn=limitx*limity
def find(dataid,left,right):
    #print(threshold)
    global minn,a,b
    localminn=100000000
    if len(dataid)<threshold or right-left<10:
        for i in dataid:
            for j in dataid:
                dis=(data[i][0]-data[j][0])*(data[i][0]-data[j][0])+(data[i][1]-data[j][1])*(data[i][1]-data[j][1])
                dis=math.sqrt(dis)

                if dis==0:
                    continue
                if dis<minn:
                    a=i
                    b=j
                    minn=dis
                    localminn=dis
        return localminn
    mid=(left+right)/2
    leftid=[]
    rightid=[]
    for i in dataid:
        if data[i][0]<mid:
            leftid.append(i)
        else:
            rightid.append(i)
    resultl=find(leftid,left,mid)
    resultr=find(rightid,mid,right)
    d=min(resultr,resultl)
    middleleftid=[]
    middlerightid=[]
    for i in leftid:
        if data[i][0]>mid-d:
            middleleftid.append(i)
    for i in rightid:
        if data[i][0]<mid+d:
            middlerightid.append(i)
    for i in middleleftid:
        for j in middlerightid:
            if data[i][1] - data[j][1]>d:
                continue
            dis = (data[i][0] - data[j][0]) * (data[i][0] - data[j][0]) + (data[i][1] - data[j][1]) * (
                        data[i][1] - data[j][1])
            dis = math.sqrt(dis)
            if dis < minn:
                a = i
                b = j
                minn = dis
                localminn = dis
    return localminn
timestart=time.time()
find([i for i in range (datanum)],0,limitx)
timeend=time.time()
print(a)
print(b)
print(minn)
plt.clf()
plt.scatter(datax,datay,c='black')
size=0.01
plt.scatter(data[a][0],data[a][1],c='red')
plt.scatter(data[b][0],data[b][1],c='green')
plt.show()
print('timecost'+str(timeend-timestart))
dataid=[i in range (datanum)]
timestart=time.time()
for i in dataid:
    for j in dataid:
        dis = (data[i][0] - data[j][0]) * (data[i][0] - data[j][0]) + (data[i][1] - data[j][1]) * (
                    data[i][1] - data[j][1])
        dis = math.sqrt(dis)

        if dis == 0:
            continue
        if dis < minn:
            a = i
            b = j
            minn = dis

timeend=time.time()
print(a)
print(b)
print(minn)
print('timecost'+str(timeend-timestart))

 

上一篇:用AOP思想改造一个服务器的数据存储


下一篇:1019 数字黑洞 (20分)/1069 The Black Hole of Numbers (20分)