Ugly Gardon

世界因我而不同

Python networkx 实现网络流

最近帮同学做作业……发现国外的算法平台确实做得很完善……

在这个平台里,你可以写一些脚本让文件相互调用,对于现有的算法,比如跑最大流的ford-fulkerson算法,可以很轻松地调用已有的算法包来实现……简直是健忘星人的福音……还要啥自行车……当然我不知道这个复杂度为什么是O(m2logC)……

To aid you in your task you have been provided with an implementation of the Ford-Fulkerson algorithm. You may assume without proof that this algorithm correctly returns the maximum flow of a given flow network G in O(m2logC) time using O(n+m) space, where C is maximum flow in G.


# ford-fulkerson.py

# this is a simple script to print a graph's maximum flow
# you can pipe the output of your pre-processing script to this
# script if you don't want to run ford-fulkerson in your script
# flow is computed between vertex 0 and vertex n-1

# expected input format:
# n
# m
# vertexId vertexId capacity
# vertexId vertexId capacity
# ...
# vertexId vertexId capacity

import networkx as nx

g = nx.DiGraph()

n, m = int(input()), int(input())

for i in range(n):
    g.add_node(i)

for _ in range(m):
    a, b, c = [ int(i) for i in input().split(' ') ]
    g.add_edge(a, b, capacity=c)

max_flow = nx.algorithms.flow.maxflow.maximum_flow(g, 0, n-1)[0]
print(max_flow)

为了调用它,可以先写一个C++程序做个小测试

// a1.cc
#include <string>
#include <iostream>
using namespace std;
int main() {
    string str = "4\n5\n0 1 3\n1 3 2\n0 2 2\n2 3 3\n0 3 1\n";
    cout << str;
    return 0;
}

Linux后台,配置文件为build.sh进行编译

#! /usr/bin/env bash

# C
# clang a1.c -o a4

# C++
clang++ a1.cc -o a4

# Java
# javac A4.java

以及run.sh运行

#! /usr/bin/env bash

# C/C++
./a4 | python3 ford-fulkerson.py

# Java
# java A4 | python3 ford-fulkerson.py

# Python
# python3 a4.py

答案是5.

所以我们的工作量就变成了……只需要建图就好咯!

阅读更多
版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/Danliwoo/article/details/78219610
文章标签: python 算法
个人分类: Python |--图论
想对作者说点什么? 我来说一句

networkx网络流量监控软件

2011年01月21日 1.52MB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭