Created
April 28, 2016 21:13
-
-
Save lassik/9306feea436bd912ff83cd6f0c5d91c4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import argparse | |
| from collections import defaultdict | |
| TRUCK_WEIGHT = 8 | |
| def ints(line): | |
| return tuple(map(int, line.split())) | |
| def parse(stream): | |
| lines = list(map(ints, stream)) | |
| assert len(lines) > 2 | |
| firstline, weightlines, lastline = lines[0], lines[1:-1], lines[-1] | |
| assert len(firstline) == 2 | |
| nnodes, nroads = firstline | |
| assert 1 <= nnodes < nroads | |
| assert nroads == len(weightlines) | |
| assert len(lastline) == 1 | |
| goalnode, = lastline | |
| assert 1 <= goalnode <= nnodes | |
| def parse_weight(line): | |
| assert len(line) == 3 | |
| src, dst, weight = line | |
| assert 1 <= src <= nnodes | |
| assert 1 <= dst <= nnodes | |
| assert src != dst | |
| assert weight > 0 | |
| return src, dst, weight | |
| weights = defaultdict(dict) | |
| for src, dst, weight in map(parse_weight, weightlines): | |
| weights[src][dst] = weight | |
| return weights, goalnode | |
| def maxroadweight(weights, src, dst, route): | |
| route = route + [src] | |
| fromsrc = weights[src] | |
| if dst not in fromsrc: | |
| nextweights = set( | |
| min(nextweight, maxroadweight(weights, nextnode, dst, route)) | |
| for nextnode, nextweight in fromsrc.items() | |
| if nextnode not in route) | |
| fromsrc[dst] = max(nextweights) if nextweights else 0 | |
| ans = fromsrc[dst] | |
| if ans: print(src, "to", dst, "maxweight =", ans) | |
| return ans | |
| def maxloadweight(weights, goalnode): | |
| return max(0, maxroadweight(weights, 1, goalnode, []) - TRUCK_WEIGHT) | |
| def description(maxweight): | |
| return "Max weight = {}".format(maxweight) if maxweight else "No route" | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("file") | |
| args = ap.parse_args() | |
| print(description(maxloadweight(*parse(open(args.file))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment