福特-富尔克森算法

福特-富尔克森方法(英語:Ford–Fulkerson method),又稱福特-富尔克森算法Ford–Fulkerson algorithm),是一类计算网络流最大流贪心算法。之所以称之为“方法”而不是“算法”,是因为它寻找增广路径的方式并不是完全确定的,而是有几种不同时间复杂度的实现方式[1][2]。它在1956年由小萊斯特·倫道夫·福特德爾伯特·雷·富爾克森[3]发表。“福特-富尔克森”这个名词通常也指代埃德蒙兹-卡普算法,这是一个特殊的福特-富尔克森算法实现。

算法的思想如下:只要有一条从源点(开始节点)到汇点(结束节点)的路径,在路径的所有边上都有可用容量,就沿着这条路径发送一个流,流量由路径上的最小容量限制。 然后再找到另一条路径,一直到网络中不存在这种路径为止。 一条有可用容量的路径被称为一条增广路径。

算法

为一个图,并且为每条从的边设置一个最大流量,并且初始化当前流量。下面是该算法每一步的实现:

容量限制: 每条边上的流都不能超出边的最大流量。
反向对称: 的流量一定是从的流量的相反数(见样例)。
流量守恒: 除非是源点或汇点,一个节点的净流量为零。
f的值: 从源点流出的流量一定等于汇点接收的流量。

这意味着每轮计算之后通过网络的都是一个流。我们定义残留网络 是一个网络的剩余流量。注意残留网络可以设置从的流量,即使在原先的网络中不允许这种情况产生:如果 ,那么:也即,从的流量给从的流量提供了额外的剩余量。

伪代码

算法 福特-富尔克森

输入 给定一张边的容量为的图,源点以及汇点
输出 在网络中,从的最大流
  1. 初始化网络流量、残留网络。对于图的每一条边,初始化流量
  2. 只要中还存在一条从的路径,使对于每一条边,都有
    1. 设置路径本次应发送的流量为路径最小剩余流量:
    2. 更新网络流量
    3. 对于每一条边,更新的剩余流量:
      1. 在路径中“发送”流)
      2. 这个流在之后可以被“发送”回来)

步骤2中的路径可以用广度优先搜索深度优先搜索中找到。如果使用了广度优先搜索,这个算法就是Edmonds–Karp算法

当步骤2中找不到可行路径时,就无法在残留网络中到达。设是在残留网络中可以到达的节点的集合,然后从的其余部分的网络一方面等于我们找到的从的所有流的总流量,另一方面所有这样的流量组成了一个上限。这说明我们找到的流是最大的。参见最大流最小割定理

如果图有多个源点和汇点,可以按如下方法处理:设。 添加一个新源点与所有源点有一条边相连,容量。添加一个新汇点与所有汇点 有一条边相连,容量。然后执行福特-富尔克森算法。

同样的,如果节点有通过限制,可将这个节点用两个节点替换,用一条边相连,容量为。然后执行福特-富尔克森算法。

复杂度

算法通过添加找到的增广路径的流量增加总流量,当无法找到增广路径时,总流量就达到了最大。当流量是整数时,福特-富尔克森算法的运行时间为(参见大O符号), 图中的边数,为最大流。 这是因为一条增广路径可以在的时间复杂度内找到,每轮算法执行后流量的增长至少为。但是在极端情况下,算法有可能永远不会停止。

福特-富尔克森算法的一个特例是埃德蒙兹-卡普算法,时间复杂度为

样例

下面的样例演示了福特-富尔克森在一张有4个节点,源点为,汇点为的图中的第一轮计算。 这个例子显示了算法在最坏情况下的行为。在每一轮算法中,只有的流量被发送至网络中。如果算法改用宽度优先搜索,那么只需要两轮计算。

路径 容量 网络
原流
1998轮之后…
最终流

注意当找到路径时,流是如何从发送至的。

无法终止算法的样例

右图所示的网络中源点为,汇点为的容量为, ,使。其它所有边的容量。 使用福特-富尔克森算法可找到三条增广路径,分别为.

步骤 增广路径 发送流 剩余容量
0
1
2
3
4
5

注意在步骤1和步骤5之后,边的残留容量都可以表示为,同时,对于一些特殊的这意味着算法可以通过无限增广,并且残留容量总处于一个循环。在步骤5之后网络的流为,如果继续用以上的算法增广,总的流将向趋近,但最大流为。在这个样例中,算法将永远不会停止,且结果也不会向实际的最大流趋近。[4]

Python源码

class Edge(object):
    def __init__(self, u, v, w):
        self.source = u
        self.sink = v  
        self.capacity = w
    def __repr__(self):
        return "%s->%s:%s" % (self.source, self.sink, self.capacity)

class FlowNetwork(object):
    def __init__(self):
        self.adj = {}
        self.flow = {}
 
    def add_vertex(self, vertex):
        self.adj[vertex] = []
 
    def get_edges(self, v):
        return self.adj[v]
 
    def add_edge(self, u, v, w=0):
        if u == v:
            raise ValueError("u == v")
        edge = Edge(u,v,w)
        redge = Edge(v,u,0)
        edge.redge = redge
        redge.redge = edge
        self.adj[u].append(edge)
        self.adj[v].append(redge)
        self.flow[edge] = 0
        self.flow[redge] = 0
 
    def find_path(self, source, sink, path):
        if source == sink:
            return path
        for edge in self.get_edges(source):
            residual = edge.capacity - self.flow[edge]
            if residual > 0 and edge not in path:
                result = self.find_path( edge.sink, sink, path + [edge]) 
                if result != None:
                    return result
 
    def max_flow(self, source, sink):
        path = self.find_path(source, sink, [])
        while path != None:
            residuals = [edge.capacity - self.flow[edge] for edge in path]
            flow = min(residuals)
            for edge in path:
                self.flow[edge] += flow
                self.flow[edge.redge] -= flow
            path = self.find_path(source, sink, [])
        return sum(self.flow[edge] for edge in self.get_edges(source))

使用样例

>>> g = FlowNetwork()
>>> [g.add_vertex(v) for v in "sopqrt"]
[None, None, None, None, None, None]
>>>
>>> g.add_edge('s','o',3)
>>> g.add_edge('s','p',3)
>>> g.add_edge('o','p',2)
>>> g.add_edge('o','q',3)
>>> g.add_edge('p','r',2)
>>> g.add_edge('r','t',3)
>>> g.add_edge('q','r',4)
>>> g.add_edge('q','t',2)
>>> print (g.max_flow('s','t'))
5

应用

二分图的最大匹配

最大不相交路径

参考文献

  1. ^ Laung-Terng Wang, Yao-Wen Chang, Kwang-Ting (Tim) Cheng. Electronic Design Automation: Synthesis, Verification, and Test. Morgan Kaufmann. 2009: 204. ISBN 0080922007. 
  2. ^ Thomas H. Cormen; Charles E. Leiserson; Ronald L. Rivest; Clifford Stein. Introduction to Algorithms. MIT Press. 2009: 714. ISBN 0262258102. 
  3. ^ Ford, L. R.; Fulkerson, D. R. Maximal flow through a network. Canadian Journal of Mathematics. 1956, 8: 399. doi:10.4153/CJM-1956-045-5. 
  4. ^ Zwick, Uri. The smallest networks on which the Ford–Fulkerson maximum flow procedure may fail to terminate. Theoretical Computer Science. 21 August 1995, 148 (1): 165–170. doi:10.1016/0304-3975(95)00022-O. 

Read other articles:

Osmeriformes Osmerus mordax Klasifikasi ilmiah Kerajaan: Animalia Filum: Chordata Kelas: Actinopterygii Superordo: Osmeromorpha Ordo: Osmeriformes Spesies tipe Osmerus eperlanus(Linnaeus, 1758) Famili Lihat teks Osmeriformes /ɒsˈmɛrɪfɔːrmiːz/ adalah salah satu ordo ikan bersirip kipas. Nama ordonya berarti berbentuk bau, diambil dari Osmerus (salah satu genusnya) + kata akhiran ordo ikan formes. Kata tersebut berasal dari bahasa Yunani Kuno ὀσμή (osmé atau bau menyengat) + bahasa...

 

منتخب غواتيمالا لكرة القدم (بالإسبانية: Selección de fútbol de Guatemala)‏  معلومات عامة بلد الرياضة  غواتيمالا الفئة كرة القدم للرجال  رمز الفيفا GUA  الاتحاد اتحاد غواتيمالا لكرة القدم كونفدرالية كونكاكاف (أمريكا الشمالية) الملعب الرئيسي ملعب ماتيو فلوريس الموقع الرسمي الموق

 

Царь Картли-Кахетиигруз. ქართლ-კახეთის მეფე Герб династии Багратиони Давид XII Должность Резиденция Тбилисский дворец, Тбилиси Назначались по наследию Предшествующая Царь КахетииЦарь Картли Появилась 8 января 1762 Первый Ираклий II Последний Давид XII Заменившая Тиф

Невідомий, якого знали всі Жанр військовийРежисер Володимир ЛуговськийУ головних ролях Петро ГлєбовВолодимир ДружниковОператор Олександр Суський, Микола ІлюшинКомпозитор Євген ЗубцовКінокомпанія «Укртелефільм»Країна  СРСРРік 1972IMDb ID 5316222 «Невідомий, якого знал...

 

Дзяржаўны гімн Беларускай Савецкай Сацыялiстычнай РэспублiкiB. Indonesia: Lagu Kebangsaan RSS ByelorusiaLagu kebangsaan  RSS ByelorusiaPenulis lirikMihas' KlimovichKomponisNestar SakalowskiPenggunaan1955Pencabutan1991Sampel audioVokalberkasbantuan Lagu Kebangsaan Republik Sosialis Soviet Byelorusia (bahasa Belarus: Дзяржаўны гімн Беларускай Савецкай Сацыялiстычнай Рэспублiкi; ...

 

Desmond Tutu Ubuntu theology is a Southern African Christian perception of the African Ubuntu philosophy that recognizes the humanity of a person through a person's relationship with other persons.[1] It is best known through the writings of the Anglican archbishop Desmond Tutu, who, drawing from his Christian faith, theologized Ubuntu by a model of forgiveness in which human dignity and identity are drawn from the image of the triune God. Human beings are called to be persons because...

Public high school in Mahanoy City, Schuylkill County, Pennsylvania, United StatesMahanoy Area Junior Senior High SchoolMap of school districts in Schuylkill County, PennsylvaniaAddress1 Golden Bear DriveMahanoy City, Schuylkill County, Pennsylvania 17948United StatesInformationTypePublic high schoolPrincipalStanley Sabol Jr.Faculty30 teachers (2013)[1]Grades9-12Enrollment271 pupils (2016)[2]MascotGolden BearWebsitehttp://www.mabears.net/ Mahanoy Area Junior Senior High School...

 

Brain region responsible for colour processing This article is about the brain region. For the crystallographic defect, see Color center (crystallography). Colour centreColour vision area shown as V8 on upper imageAnatomical terminology[edit on Wikidata] The colour centre is a region in the brain primarily responsible for visual perception and cortical processing of colour signals received by the eye, which ultimately results in colour vision. The colour centre in humans is thought to be ...

 

Ruprecht von der Pfalz auf einem Gemälde im Fürstengang Freising Wappentafel von Ruprecht von der Pfalz im Fürstengang Freising Rup(p)recht von der Pfalz (auch Ruprecht der Tugendhafte; * 14. Mai 1481 in Heidelberg; † 20. August 1504 in Landshut), stammte aus der pfälzischen Linie der Wittelsbacher. Seine Eltern waren Philipp der Aufrichtige, Kurfürst von der Pfalz und Margarete von Bayern-Landshut. Inhaltsverzeichnis 1 Leben 2 Stammbaum 3 Einzelnachweise 4 Literatur Leben Ruprecht, ge...

1995 Indian filmHathkadiPromotional PosterDirected byTatineni Rama RaoStory byKaraikudi NarayananProduced byA. V. SubbaraoStarringGovindaShilpa ShettyShakti KapoorCinematographyPrasadbabuEdited byGowtham RajuMusic byAnu MalikProductioncompanyPrasad Art ProductionsRelease date 31 March 1995 (1995-03-31) CountryIndiaLanguageHindiBudget₹3 crore[1]Box office₹8,29 crore[1] Hathkadi (transl. Handcuffs) is a 1995 Hindi-language action film directed by T. Rama...

 

School of Islam dominant in Oman For other uses, see Ibadi (disambiguation). Ibadi Islamالإباضية‎al-ʾIbāḍiyyaThe Ibadi Mosque of Guellala in Jerba, TunisiaTypeSchool of IslamClassificationKharijismTheologyMonotheismLanguageClassical ArabicTerritoryMajority in:  OmanMinority in: Algeria (Mzab) Libya (Nafusa) Tunisia (Djerba) Tanzania (Zanzibar)FounderAbdallah ibn IbadOriginc. 692 AD Basra, Umayyad CaliphateMembersc. 2.72 million[1] – 7...

 

Luftbild der Anstalt (2015) Informationen zur Anstalt Name Justizvollzugsanstalt Iserlohn Bezugsjahr 1970 Haftplätze 282[1] Mitarbeiter ca. 200[2] Anstaltsleitung Beatrix Mühlhans Website www.jva-iserlohn.nrw.de Eingangsbereich Die Justizvollzugsanstalt Iserlohn ist eine Jugendstrafanstalt in Iserlohn, in der Frauen und Männer die das vierzehnte Lebensjahr vollendet haben und das vierundzwanzigste Lebensjahr noch nicht vollendet haben eine Jugendstrafe oder eine Freiheitsst...

List of English historic buildings Manchester is a city in Northwest England. The M1 postcode area of the city includes part of the city centre, in particular the Northern Quarter, the area known as Chinatown, and part of the district of Chorlton-on-Medlock. The postcode area contains 193 listed buildings that are recorded in the National Heritage List for England. Of these, 14 are listed at Grade II*, the middle of the three grades, and the others are at Grade II, the lowest g...

 

Korean-American musician Johan KimBackground informationBirth nameGeorge Han KimBorn (1973-03-27) March 27, 1973 (age 50)Atlanta, Georgia, United StatesGenresK-pop, R&B, SoulOccupation(s)Singer, record producer, song writerInstrument(s)VocalsYears active1993–presentLabelsSoul Family Production Korean nameHangul김조한Revised RomanizationGim Jo-hanMcCune–ReischauerKim Cho-han George Han Kim (born March 27, 1973), better known by his Korean name, Johan Kim (Korean: 김조한), is...

 

Departamentos del sur del Primer Imperio Francés en 1811 El departamento del Trasimeno (en italiano, dipartamento del Trasimeno; en francés, département du Trasimène) fue un antiguo departamento situado en al sur de la actual región italiana de Umbría creado por la República Romana entre 1798 y 1799, tomando su nombre del lago homónimo y teniendo por capital la ciudad de Perugia. Con el regreso del gobierno pontificio en 1799 el departamento fue disuelto, hasta la anexión de los Esta...

Pour les articles homonymes, voir FMM. Force multinationale mixte(en) Multinational Joint Task Force Badge de la FM/MNJTF Création 1994 Allégeance Union africaine Effectif 8 700 militaires, policiers et civils[1] Composée de Forces béninoises Forces camerounaises Forces nigériennes Forces nigérianes Forces tchadiennes Garnison N'Djaména (Tchad) Guerres Insurrection de Boko Haram Commandant C.O. Ude modifier  La Force multinationale mixte[2] (FMM) est une force armée composé...

 

1924 film by Rupert Hughes True As SteelPosterDirected byRupert HughesWritten byRupert HughesProduced byGoldwyn PicturesStarringAileen PringleHuntley GordonCinematographyJohn J. MescallDistributed byGoldwyn PicturesRelease date April 20, 1924 (1924-04-20) Running time70 minutesCountryUnited StatesLanguageSilent (English intertitles) True As Steel is a 1924 American silent drama film directed and written by Rupert Hughes which stars Aileen Pringle and Huntley Gordon.[1] ...

 

Not to be confused with King Kong Lam. King Kong LeeBorn李信樵 (1981-01-19) 19 January 1981 (age 42)TaiwanOccupation(s)Actor, Comedian, HostYears active2002–present Lee Hsin Chiao (李信樵), known professionally by his stage name King Kong Lee (Chinese: 金剛; pinyin: Jīn Gāng; born 19 January 1981), is a Taiwanese actor and comedian. He hosted the popular Super Trio series[1] and has played some notable roles in some dramas such as No Regrets as a Japa...

Canadian alt-right political activist (born 1995) Lauren SouthernSouthern in 2016BornLauren Cherie Southern (1995-06-16) 16 June 1995 (age 28)Surrey, British Columbia, CanadaAlma materUniversity of the Fraser Valley(withdrew)OccupationPolitical activist[1]Political partyLibertarianChildren1[2]YouTube informationChannel Lauren Southern Years active2015–presentSubscribers716,000[3]Total views63 million[3] Creator Awards100,000 subscribers201...

 

Cricket in Mauritius is a sporadic affair, with occasional games arranged by enthusiastic zealots replacing any organised competition structure. Four clubs kept the game alive in Mauritius; Maurindia, Star, Spartan and United Cricket Clubs. Maurindia is arguably the leading club and twice yearly plays the Seychelle Islands representative team in reciprocal visits. The number of clubs have recently increased due to the increased popularity of the game in Mauritius and also the increase in expa...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!