# Python networkx 实现网络流

429人阅读 评论(0)

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)$O(m^2 logC)$ time using O(n+m)$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):

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

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

// 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

#! /usr/bin/env bash

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

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

# Python
# python3 a4.py

1
0

个人资料
• 访问：68867次
• 积分：1523
• 等级：
• 排名：千里之外
• 原创：79篇
• 转载：2篇
• 译文：1篇
• 评论：45条
爱唱歌的程序员
最新评论