google code jam exercise——Rope Intranet
Round 1C 2010,C轮的测试题了。本以为难度会加大,不过第一题还是比较简单的。
Rope Intranet,统计绳子的交点个数。算法很直接,遍历所有的绳子,累计它与剩下的绳子的交点的个数。
代码如下:
#!/usr/bin/python #encoding:UTF-8 #Filename:RopeIntranet.py import sys def compareWire(a,b): if (a[0]<b[0] and a[1]>b[1]) or (a[0]>b[0] and a[1]<b[1]): return 1 else: return 0 inname = "input.txt" outname = "output.txt" if len(sys.argv)>1: inname = sys.argv[1] outname = inname.rstrip(".in") outname = outname + ".out" fin = open(inname,"r") fout = open(outname,"w") testCaseNum = int(fin.readline().rstrip("\n")) for caseNum in range(testCaseNum): wireNum = int(fin.readline().rstrip("\n")) wireData = [] for wireCnt in range(wireNum): wire = [int(val) for val in fin.readline().rstrip("\n").split()] wireData.append(wire) crossCnt = 0 for i in range(wireNum): for j in range(i+1,wireNum): crossCnt = crossCnt + compareWire(wireData[i],wireData[j]) answer = "Case #%d: %d\n" %(caseNum+1,crossCnt) fout.write(answer) fin.close() fout.close()
测试通过。不过在测试large case的时候时间有点长,有更快的算法么?