出租车几何任务

时间:2014-12-26 21:55:16

标签: geometry distance computational-geometry

所以,我已经在这项任务中挣扎了一段时间。听起来像这样:给定N点(X,Y)X,Y整数和形式P(A,B)的M个问题,找到从点P(A,B)到所有N个给定点的总距离。从A(x1,y1)到B(x2,y2)的距离= max(| x1-x2 |,| y1-y2 |)。也许这听起来很奇怪,我不是一个说英语的人,对于这些错误感到抱歉。我将离开这里IN / OUT



IN.txt (N = 4, M = 3, the first 4 coordinates represent the given points. 
the next 3 coordinates are the points from which i have to compute the total lenght)
4  3
3 5
-3 -2
1 4
-4 -3
2 -4 
1 4
4 2

OUT.txt
28
15
21




1 个答案:

答案 0 :(得分:0)

这里有一些Python可以帮到你。在写作时一定要注意你所在的目录,这样你就不会覆盖。

我已根据您在问题中提供的输入信息对其进行了测试,并且可以正常工作,并根据需要提供格式化的输出文件。

# Assuming you're in the directory to IN.txt -- otherwise, insert the filepath.
input_file = open("IN.txt", "r")

# Read the input file and split it by new lines
input_lines_raw = input_file.read().split('\n')

input_file.close()


# Split the input lines and eliminate the spaces/create the vector int lists
input_lines_split = []

for element in input_lines_raw:
    input_lines_split.append(element.split(' '))

input_lines = []

for sub in input_lines_split:
    inserter = []
    for elem in sub:
        if (len(elem) > 0):
            inserter.append(elem)
    input_lines.append(inserter)

input_lines = [[int(j) for j in i] for i in input_lines]


# Build the original and final vector arrays
origin_vectors = []
dest_vectors = []

for i in range(1, input_lines[0][0] + 1):
    dest_vectors.append(input_lines[i])

for i in range(input_lines[0][0] + 1, input_lines[0][0] + input_lines[0][1] + 1):
    origin_vectors.append(input_lines[i])

# "Distance" operations on the lists of vectors themselves/generate results array
results_arr = []

for original in origin_vectors:
    counter = 0
    for final in dest_vectors:
        counter = counter + max(abs(original[0] - final[0]), abs(original[1] - final[1]))
    results_arr.append(counter)

print(results_arr)
for element in results_arr:
    print(str(element))

# Open the ouput file and write to it, creating a new one if it doesn't exist.
# NOTE: This will overrwrite any existing "OUT.txt" file in the current directory.
output_file = open("OUT.txt", "w")

for element in results_arr:
    output_file.write(str(element) + '\n')

output_file.close()