这给出了具有少于 n-1 个边的次优解决方案。
from numpy.random import randint
from collections import defaultdict
import copy
def create_sample(source_count=5000, sink_count=200):
diff = -1
while diff < 0:
sinks = [["b" + str(i), randint(source_count)] for i in range(sink_count)]
sources = [["a" + str(i), randint(sink_count)] for i in range(source_count)]
sink_sum = sum([x[1] for x in sinks])
source_sum = sum([x[1] for x in sources])
diff = sink_sum - source_sum
avg_refill = diff // source_count + 1
weights_match = False
while not weights_match:
for i in range(source_count):
if not diff:
break
rnd = randint(avg_refill * 2.5) if diff > 10 * (avg_refill) else diff
diff -= rnd
sources[i][1] += rnd
weights_match = sum([x[1] for x in sources]) == sum([x[1] for x in sinks])
return sources, sinks
def solve(sources, sinks):
src = sorted(copy.deepcopy(sources), key=lambda x: x[1])
snk = sorted(copy.deepcopy(sinks), key=lambda x: x[1])
res = []
while snk:
if src[0][1] > snk[0][1]:
edge = (src[0][0], *snk[0])
src[0][1] -= snk[0][1]
del snk[0]
elif src[0][1] < snk[0][1]:
edge = (src[0][0], snk[0][0], src[0][1])
snk[0][1] -= src[0][1]
del src[0]
else:
edge = (src[0][0], *snk[0])
del src[0], snk[0]
res += [edge]
return res
def test(sources, sinks):
res = solve(sources, sinks)
d_sources = defaultdict(int)
d_sinks = defaultdict(int)
w_sources = defaultdict(int)
w_sinks = defaultdict(int)
for a, b, c in res:
d_sources[a] += 1
d_sinks[b] += 1
w_sources[a] += c
w_sinks[b] += c
print("source " + ("is" if dict(sources) == w_sources else "isn't") + " source")
print("sink " + ("is" if dict(sinks) == w_sinks else "isn't") + " sink")
print(
f"source:\n \tdeg_sum = {sum(d_sources.values())}\n\tmax_deg = {max(d_sources.values())}"
)
print(
f"sink:\n \tdeg_sum = {sum(d_sinks.values())}\n\tmax_deg = {max(d_sinks.values())}"
)
这是一个示例运行:
In [1]: %run solver.py
In [2]: test(*create_sample())
source is source
sink is sink
source:
deg_sum = 5196
max_deg = 3
sink:
deg_sum = 5196
max_deg = 56
这是它如何工作的说明:
sources: 4,5,3,2
sinks: 2,7,2,2,1
sorted:
55555|44|44|33|32|2
77777|77|22|22|22|1
So we have 6 edges.
这是使用此算法的排序和未排序解决方案之间的比较:
---------------------------------------------
| (1000,1000) |
---------------------------------------------
| criteria | sorted | random order |
| source degree sum | 1991 | 1999 |
| source max degree | 3 | 7 |
| sink degreee sum | 1991 | 1999 |
| sink max degree | 3 | 8 |
---------------------------------------------
---------------------------------------------
| (200,5000) |
---------------------------------------------
| criteria | sorted | random order |
| source degree sum | 5198 | 5198 |
| source max degree | 2 | 3 |
| sink degreee sum | 5198 | 5198 |
| sink max degree | 43 | 54 |
---------------------------------------------