Python 贪婪Alg:占用开始时间到完成时间
背景信息: 给定一个建议的列表:a={a1,a2,…,ax},其中每个分配从指定的开始时间运行到指定的完成时间,请选择一个最小大小的分配集,以便从给定的S到F的所有时间都被至少一个分配占用 作业可能重叠,可能在开始时间之前开始,也可能在完成时间之后结束 唯一要求:所选作业之间无差距 所有信息以以下格式在assignments.txt文件中给出:Python 贪婪Alg:占用开始时间到完成时间,python,algorithm,sorting,shortest-path,greedy,Python,Algorithm,Sorting,Shortest Path,Greedy,背景信息: 给定一个建议的列表:a={a1,a2,…,ax},其中每个分配从指定的开始时间运行到指定的完成时间,请选择一个最小大小的分配集,以便从给定的S到F的所有时间都被至少一个分配占用 作业可能重叠,可能在开始时间之前开始,也可能在完成时间之后结束 唯一要求:所选作业之间无差距 所有信息以以下格式在assignments.txt文件中给出: 2 8 // the first line gives the start time and end time 5 //
2 8 // the first line gives the start time and end time
5 // the second line gives the number of assignments to choose from
1 1 3 // the subsequent lines give the assignment number, start time, and finish time
2 2 6
3 5 7
4 6 9
5 5 10
如何在python中为这个算法编码
我的想法是:
读取文本文件并存储到数组中。根据其各自的属性分离数组元素,然后为贪婪alg编码,即在开始和完成时间内连续拾取最长的分配
这就是我到目前为止所做的:
def readFile():
file = open( "assignments.txt", "r" )
unsortedArray = []
for line in file:
toInt = map(int,line.split())
unsortedArray.append(toInt)
print unsortedArray
return unsortedArray
def sortArray(unsortedArray):
for i in range(2, len(unsortedArray)):
if unsortedArray[i][1] > unsortedArray[i+1][1]:
unsortedArray[i],unsortedArray[i+1] = unsortedArray[i+1],unsortedArray[i]
print unsortedArray[i]
def main():
readFile()
sortArray(readFile())
main()
“…可在开始时间之前开始,在结束时间之后结束”。如果这是真的,那么您可以贪婪地选择最大的一组作业,以满足所需的时间间隔,并连续运行它们。实际开始和结束时间无关;只有这两者之间的区别才有意义。@chepner这是一个很好的观点,但是我在用java编写代码时遇到了麻烦。如果这是关于java的,请删除Python标记。如果语言不重要,请删除这两个标记。如果您认为有必要,也可以使用“语言不可知”标签。@m69我的道歉。必要时进行编辑