Федеральное агентство по образованию РФ. Тверской государственный технический университет Кафедра высшей математики
Про...
26 downloads
173 Views
2MB Size
Report
This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Report copyright / DMCA form
Федеральное агентство по образованию РФ. Тверской государственный технический университет Кафедра высшей математики
Пронькин Ю.С., Егоров Ю.А.
Элементы теории графов и их технические приложения.
Учебно-методическое пособие для студентов технических специальностей. Часть 1
Тверь 2007
2
УДК 519.17 ББК 22.17
В пособии рассматриваются основные понятия теории графов и их приложения к описанию и решению различных технических задач. Предназначено для студентов технических специальностей, в программу которых входит изучение раздела «графы».
Элементы теории графов и их технические приложения. Учебно-методическое пособие для студентов технических специальностей. Часть 1. Составители: Пронькин Ю.С., Егоров Ю.А.
Технический редактор Комарова Г.В. Подписано в печать Физ.печ.л. 3,5 Усл.печ. л. 3,26 Уч.-изд. л. 3,05 Редакционно-издательский центр ТГТУ 170026, г. Тверь, наб. А.Никитина, 22 © Тверской государственный технический университет, 2007 © Пронькин Ю.С., Егоров Ю.А., 2007
3
Оглавление Введение ……………………………………………………………………… 4 стр. I. Графы – форма моделирования структур ……….………………………….. 4 стр. II. Графы и способы их задания 1. Графы. Различные типы графов……………………………………………. 6 стр. 2. Операции над графами ……………………………………………………. 12 стр. 3. Маршруты, циклы и связность …………………………………………… 14 стр. 4. Характеристики графов …………………………………………………….16 стр. 5. Представление графов с помощью матриц ………………………………. 17 стр. 6. Деревья ……………………………………………………………………….20 стр. 7. Полюсные графы 7.1 Физические системы с сосредоточенными компонентами ……………...23 стр. 7.2 Полюсные графы ..…………………………………………………………24 стр. 7.3 Электрические цепи ……………………………………………………….25 стр. 7.4 Механические поступательные системы ………………………………….27 стр. 7.5 Механические вращательные системы ……………………………………29 стр. 7.6 Пневматические системы …………………………………………………..31 стр. 7.7 Аналогии …………………………………………………………………….33 стр. 7.8 Нелинейные и параметрические компоненты …………………………….34 стр. 8. Многополюсные компоненты 8.1 Полюсный граф многополюсника ………………………………………....36 стр. 8.2 Уравнение многополюсника ……………………………………………….37 стр. 8.3 Электронная лампа ………………………………………………………….38 стр. 8.4 Транзистор …………………………………………………………………...39 стр. 8.5 Трансформатор ………………………………………………………………40 стр. 8.6 Механические многополюсники …………………………………………...41 стр. 8.7 Дифференциальный редуктор ……………………………………………. 43 стр. 8.8 Двигатель постоянного тока ………………………………………………..44 стр. 8.9 Гидромеханические многополюсники……………………………………...45 стр. 9. Задача о кратчайшем пути ……………………………………………………. 47 стр. 10. Кратчайший путь на ориентированном графе ……………………………….50 стр. 11. Постановка исследований оптимальных задач при наличии ограничений ..52 стр. 12. Понятие о сетевом планировании …………………………………………….54 стр. Литература ………………………………………………………………………. 57 стр.
4
Введение Теория графов служит математической моделью для всякой системы, содержащей бинарное отношение. В теоретико-графовых терминах формулируется большое число задач, связанных с дискретными объектами. Они являются универсальной структурной моделью различных физических систем, при изучении которых на первый план выступает характер соединений различных ее компонентов, т.е. связи и отношения между объектами (электрическими, механическими, пневматическими, химическими, биологическими, биофизическими, социологическими и др.). Они используются в задачах проектирования и конструирования, анализе надежности сетей связи, электронных схем, коммуникационных сетей, при решении транспортных задач о перевозках, планировании и управлении, при составлении оптимальных маршрутов доставки грузов, при моделировании сложных технологических процессов, генетике, психологии, социологии, экономике и т.д. Преимущество графов следует из того, что они однозначно описывают структуру системы, на их основе просто записываются канонические уравнения, фиксируются физические свойства и причинная зависимость между переменными. Их особенностью является геометрический подход к изучению объектов, т.е. представление в виде диаграмм.
I.
Граф – форма моделирования структур.
В инженерной практике рассматриваются технические системы, которые представляют собой комплекс взаимосвязанных технических средств, обеспечивающих преобразование массы, энергии и информации. Существенным элементом при этом является установление отношений между входами и выходами технических средств. Комплекс этих отношений и образует систему. Выделяют два типа отношений: отношения преобразования и отношения связей. Отношения преобразования включают отношения переработки (информации, массы, с изменением свойств материала (внутренней и внешней структуры), преобразование энергии) и отношения перемещения (изменение положения предмета по отношению к другим предметам). Отношение связи – это то, что объединяет функциональные элементы технической системы в одно целое. Они бывают только жесткими, т.е. не изменяющимися, в процессе функционирования системы. Через связи проходит интенсивный обмен веществом, энергией и информацией с окружающей средой и между элементами технической системы. Отношения связи отражают все взаимоотношения в технической системе и не обладают собственной материальной основой. F Под элементом системы будем понимать пару элементов I ⎯⎯→ О, где F характеризует преобразование. Рассмотрим блок-схему комплекса, в котором имеется несколько элементов, обеспечивающих ее действие в соответствии с отношением преобразований (при одновременном существовании отношения связей).
5
Рис. 1 Элементы от 1 до 5образуют комплекс, входящий как составная часть в совокупность С. Между действующим комплексом и этой совокупностью имеется отношение связи, которое обусловлено тем что вход Ос совокупности одновременно представляет собой и I. Отношение между комплексом и совокупностью раскрывает связь О5=Iс. Аналитическая запись отношений преобразований и отношений связей как комплекса, образующего систему выглядит следующим образом: Ос= I1 → O1=I12 → O2=I3 → O 13 =I5 → O5=Ic
↑ ↓ 11 I 2 =O4 ← I4=O 11 3 Рассмотренная система представляет собой последовательно-итерационный F комплекс, т.к. включает преобразование I4 ⎯⎯→ О4, дающее основу действия элемента 4 (случай обратной связи), характерного для автоматизированных комплексов. Действие элементов 2 и 4 оказывается сложным, поскольку в элементе 2 F F О2 и I 11 ⎯→ О2, где I 12 =О1; действие осуществляется на основе отношений I 12 ⎯⎯→ 2 ⎯ I 11 2 =О4. F F О 13 и I 3 ⎯⎯→ О 11 Для элемента 3 существует обратное явление I 3 ⎯⎯→ 3 , где
О 13 =I5; O 11 3 =I4. Для рассмотренной выше блок-схемы (рис. 1) используется еще одна форма записи – граф. В этой форме записи блоки соответствуют вершинам графа и
Рис. 2 обозначают отношения преобразований. Второй элемент графа - ребра (отрезки, соединяющие вершины) обозначают отношения связей. Можно построить обратный граф (рис. 3), в котором отношения
6
Рис. 3 преобразований обозначены ребрами, а отношения связей – вершинами. В этом случае вершинам соответствуют тождественные пары входов и выходов потоков энергии, массы или информации.
II.
Графы и способы их задания.
1. Графы. Различные типы графов. Многие прикладные задачи сводятся к рассмотрению совокупностей некоторых объектов, находящихся во взаимной связи и взаимодействии. Например, при изучении электрических цепей существенным может оказаться характер соединений различных ее компонентов; органические молекулы образуют структуры, характерными свойствами которых являются связи между атомами; различные связи и отношения между людьми, событиями, также могут представлять интерес. В подобных случаях принято, рассматриваемые объекты изображать точками, называемыми вершинами, а связи между ними – линиями (произвольной конфигурации), соединяющими их и называемыми ребрами. Графом называют множество вершин V, связи между которыми определены множеством ребер Е. Таким образом, граф G, обозначенный как G=(V,Е), представляет собой пару (V, Е), где V – непустое множество элементов, Е – некоторое подмножество множества V(2) всех его двухэлементных подмножеств. Будем рассматривать только конечные графы, т.е. предполагаем множество V конечным. Множество вершин графа G обозначим символом VG, а множество ребер графа G – символом ЕG. Вершины и ребра графа называются его элементами. Число |VG| вершин графа G называется его порядком и обозначается через |G|. Если |G|=n, |EG|=m, то G называют (n, m) – графом. Две вершины u и v графа называются смежными, если множество {u,v} является ребром; в противном случае вершины называются не смежными. Если е={u,v} – ребро, то вершины u и v называют его концами, а также, что ребро е соединяет вершины u и v. Такое ребро обозначается символом uv. Два ребра называются смежными, если они имеют общий конец. Вершина v и ребро е называются инцидентными, если v является концом ребра е ( т.е. е=uv), и не инцидентными в противном случае.
7
Следует иметь в виду, что смежность есть отношение между однородными элементами графа, тогда как инцидентность является отношением между разнородными элементами. Множество всех вершин графа G, смежных с некоторой вершиной v, называется окружением вершины v и обозначается NG(v) или N(v). Обычно граф представляется диаграммой, состоящей из точек и линий, соединяющих некоторые из этих точек. При этом точки соответствуют вершинам графа, а соединяющие пары точек линии – ребрам. Часто эту диаграмму и называют графом. В качестве примера рассмотрим (5,6) граф (рис. 4). Для него множество вершин VG ={1,2,3,4,5} и множество ребер EG={{1,2}, {1,5}, {2,3}, {2,4}, {2,5}, {4,5}}. Вершины 1 и 2 смежны, а 1 и 3 не смежны. Вершина 1 и ребро {1,2} инциденты. Окружение вершины 2 есть N(2)={1,3,4,5}.
Рис. 4 Граф G называется полным, если любые две его вершины смежны (соединены ребром). Полный граф порядка n обозначается символом Кn, число n(n − 1) . На рис. 5 изображены полные графы К1, К2, ребер в таком графе равно С n2 = 2 К3, К4, К5.
Рис. 5 Граф называется пустым, если в нем нет ребер. Пустой граф порядка n обозначается Оn. Для задания полного графа достаточно знать число его вершин. Набор подмножеств множества S называется покрытием множества S, если объединение этих подмножеств совпадает с S. Покрытие называется разбиением, если никакие два из входящих в него подмножеств не пересекаются. Граф называется двудольным, если существует такое разбиение множества его вершин на две части, что концы каждого ребра принадлежат разным частям. Если при этом любые две вершины, входящие в разные доли, смежны, то граф называется полным двудольным. Полный двудольный граф, доли которого состоят из p и q вершин, обозначается символом Кp,q. При p=1 получаем звезду К1,q. На рис. 6 изображены звезда К1,5 и полный двудольный граф К3,3.
8
Рис. 6 Аналогично двудольным определяются К-дольный и полный К-дольный графы. Поскольку в применениях теории графов существенным является то, что есть объекты (вершины графа) и связи между объектами (ребра), граф является не геометрической, а топологической фигурой, определенные свойства которой инвариантны при взаимнонепрерывном и взаимнооднозначном пространственном преобразовании. Существенные инвариантные свойства графа отражают только число вершин, число ребер (дуг) и характер связей между вершинами. Так как граф является топологической фигурой, то один и тот же граф может быть изображен различными способами: вершины можно располагать в произвольном порядке, а соединяющие их ребра проводить в виде прямых или ломаных линий, информация, содержащаяся в графе, остается одной и той же. Оформим эти соображения в виде следующего определения: Пусть G и Н – графы, а ϕ : VG → VH – биекция. Если для любых вершин u и графа G их образы ϕ (u) и ϕ (v) смежны в Н, тогда и только тогда, когда u и v смежны в G, то эта биекция называется изоморфизмом графа G на граф H. Иначе говоря два графа называют изоморфными, если они имеют одинаковое число вершин и каждой паре вершин, соединенных ребром в одном графе, соответствует такая же пара вершин, которые соединены ребром в другом графе. Если существенные свойства графа не связаны со способом его изображения или нумерацией вершин и ребер, то изоморфные графы, обычно, не различают между собой. Изоморфизм графов G и Н обозначают следующим образом: G ≅ Н. Например, три графа, представленные на рис. 7 изоморфны между собой, так же как и два графа на рис. 8, а графы на рис. 9 не изоморфны.
Рис. 7
Рис. 8
рис. 9
9
Вопрос о том, изоморфны ли два данных графа, в общем случае оказывается сложным. Очевидно, что отношение изоморфизма графов является эквивалентностью, т.е. оно симметрично, транзитивно и рефлексивно. Следовательно, множество всех графов разбивается на классы так, что графы из одного класса попарно изоморфны, а графы из разных классов не изоморфны. Изоморфные графы естественно отождествлять, т.е. считать совпадающими и изображать одним рисунком. В некоторых ситуациях приходится различать изоморфные графы и тогда вводится понятие «помеченный граф». Граф порядка n называется помеченным, если его вершинам присвоены некоторые метки. Например, номера 1,2,…,n. Отождествив каждую из вершин графа с ее номером, определим равенство помеченных графов G и Н одного и того же порядка условием: G=Н тогда, когда EG=ЕН. На рис. 5 изображены два равных помеченных графа. На рис. 10 изображены три разных помеченных графа. Чтобы подчеркнуть, что рассматриваемые графы различаются с точностью до изоморфизма, говорят: «абстрактный граф».
Рис. 10 Справедливо утверждение: число ln помеченных графов порядка n равно 2
2
Сn
.
Дополнительным графом (или дополнением) G для произвольного графа G называется граф с теми же вершинами, что и G, и с теми и только теми ребрами, которые необходимо добавить к графу G, чтобы получился полный граф. На рис. 11 изображен граф G (слева) и дополнительный к нему (справа).
Рис. 11 Очевидно, что G =G и G ≅ H , если G ≅ Н. Граф, изоморфный своему дополнению, называется самодополнительным. Иногда приходится рассматривать более общие объекты, чем определенный выше граф, в которых две вершины могут соединяться более чем одним ребром. Мультиграф – это пара (V,E), где V – непустое множество (вершин), а Е – семейство подмножества V(2) (ребер). В этом определении допускается существование кратных ребер. Дальнейшее обобщение состоит в том, что кроме кратных ребер допускаются еще петли, т.е. ребра,
10
соединяющие вершину саму с собой. Псевдограф – это пара (V, Е), где V – непустое множество (вершин), а Е – некоторое семейство неупорядоченных пар вершин (ребер), не обязательно различных. На рис. 12 приведены мультиграф (слева) и псевдограф (справа), в основе которых лежит один и тот же граф – треугольник.
Рис. 12 Часто связи между объектами характеризуются вполне определенной ориентацией. Например, на некоторых улицах допускается только одностороннее автомобильное движение, в соединительных проводах электрической цепи задаются положительные направления токов, отношения между людьми могут определяться подчиненностью или старшинством. Ориентированные связи характеризуют переход системы из одного состояния в другое, различные отношения между числами (неравенство, делимость). Для указания направления связи между вершинами графа соответствующее ребро отмечается стрелкой. Ориентированное таким образом ребро называют дугой, а граф с ориентированными ребрами – ориентированным графом (орграфом). Итак, ориентированный граф – это пара (V, А), где V – множество вершин, А – множество ориентированных ребер (дуг), А ⊆ V2 (V2 – декартов квадрат, состоящий из упорядоченных пар элементов множества V). Если а=(v1, v2) – дуга, то вершины v1 ее начало, а v2 – конец. Аналогично определяется ориентированный мультиграф. Рассматриваются также смешанные графы, у которых есть и дуги и неориентированные ребра. Для всех этих видов графов вводится понятие изоморфизма как биекции между множествами вершин, сохраняющей смежность, кратности ребер, петли и направления дуг. Направленный граф – это орграф, не имеющий симметричных пар ориентированных ребер, т.е. дуг вида (u, v) и (v, u). На рис. 13 приведены все орграфы с тремя вершинами и тремя дугами; два последних из них – направленные графы.
Рис. 13
Взвешенные графы Рассматривая отображения связей между объектами с помощью графов, можно пойти на дальнейшее обобщение, приписывая ребрам и дугам некоторые количественные значения, качественные признаки или характерные свойства,
11
называемые весами. В простейшем случае это может быть порядковая нумерация ребер и дуг, указывающая на очередность при их рассмотрении. Вес ребра (дуги) может означать длину (пути сообщения), пропускную способность (линии связи), напряжение или ток (электрической цепи), количество набранных очков (турниры), валентность связей (химические формулы), количество рядов движения (автомобильные дороги), цвет проводника (монтажная схема электронного устройства) и т.п. Вес можно приписывать не только ребрам и дугам, но и вершинам. Вес вершины может означать любую характеристику соответствующего ей объекта. Например, количество мест в кемпингах, пропускной способностью станций техобслуживания на карте автомобильных дорог, атомный вес элемента в структурной формуле, цвет изображаемого вершиной предмета, возраст человека и т.п. Особое значение для моделирования физических систем имеют взвешенные ориентированные графы, названные графами потоков сигналов или сигнальными графами. Вершины сигнального графа отождествляются с некоторыми переменными, характеризующими состояние системы, а вес каждой вершины означает функцию времени или некоторые величины, характеризующие соответствующую переменную (сигнал вершины). Дуги отображают связи между переменными, и вес каждой дуги представляет собой численное или функциональное отношение, характеризующее передачу сигнала от одной вершины к другой. Сигнальные графы находят широкое применение в теории цепей и систем, а также во многих других областях науки и техники.
Подграфы Граф Н называется подграфом (или частью) графа G, если вес его вершины и ребра принадлежит G: VH ⊆ VG, ЕH ⊆ ЕG. Если Н – подграф графа G, то говорят, что Н содержится в G. Подграф Н называется остовным подграфом (или фактором), если он содержит все вершины G: VH=VG. Если множество вершин подграфа Н есть U, а множество его ребер совпадает с множеством всех ребер графа G, оба конца которых принадлежат U, то Н называется подграфом, порожденным (или индуцированным) множеством U, и обозначается через G(U). На рис. 14 изображен граф G и три его подграфа Н1, Н2 и Н3, среди которых Н3 является остовным, а Н2 – порожденным.
Рис. 14 Важный класс подграфов составляют подграфы, полученные в результате удаления вершин. Пусть v – вершина графа G. Граф Gv=G-v получается из графа G в результате удаления вершины v и всех инцидентных ей ребер. Очевидно, что
12
Gv=G(VG\v). Аналогично можно определить граф, полученный удалением или добавлением ребра. Обозначим соответствующие графы через G-x и G+х (рис. 15).
Рис. 15 Улам высказал предположение, что набор подграфов G-vi несет полную инфор мацию о всем графе G.
2. Операции над графами Естественно стремиться представить структуру рассматриваемого графа с помощью графов меньшего размера и более простой структуры. Одна такая операция уже была рассмотрена, это удаление вершины или ребра, а также переход к подграфу. Можно из имеющихся графов получить «большие» графы с помощью операции добавления ребра. Рассмотрим другие операции над графами. Объединение. Граф Н называется объединением (или наложением) графов F и G, если VH=VF ∪ VG и ЕH=ЕF ∪ ЕG, т.е. в Н объединяются множества вершин F и G и множество ребер. Обозначается H=F ∪ G. Аналогично определяется объединение любого конечного множества графов. Соединение графов, введенное Зыковым, обозначается F+G, состоит из F ∪ G и всех ребер, соединяющих вершины графов F и G. Операции объединения и соединения графов иллюстрируются на рис. 16.
Рис. 16
Произведение. Произведением двух графов G1=(V1, E1) и G2=(V2, E2) называется граф G=G1xG2, для которого VG=V1xV2 – декартово произведение множеств вершин исходных графов, а EG определяется следующим образом: вершины (u1, u2) и (v1, v2) смежны в графе G тогда и только тогда, когда или u1=v1, а u2 и v2 смежны в G2 или u2=v2, а u1 и v1 смежны в G1 (рис. 17).
13
Рис. 17
Композиция. G=G1[G2] также имеет VG=V1xV2 в качестве множества вершин и вершина u=(u1, u2) смежна с v=(v1, v2) тогда и только тогда, когда u1 смежна с v1 или u1=v1 и u2 смежна с v2. На рис. 17 справа показаны две композиции G1[G2] и G2[G1] и графов G1 и G2 представленных слева. Очевидно, что G1[G2] и G2[G1] не изоморфны. Если G1 и G2 – это (p1, q1) и (p2, q2) – графы соответсвенно, то для каждой из определенных выше операций можно найти число вершин и число ребер в получающемся графе (см. табл. ниже). Бинарные операции над графами Операция Число вершин Число ребер Объединение G1 ∪ G2 р1+р2 q1+q2 Соединение G1+G2 р1+р2 q1+q2+р1хр2 Произведение G1хG2 р1хр2 q1xq2+р2хq1 Композиция G1[G2] р1хр2 p1xq2+р 22 хq1 Отождествление (слияние) вершин. Пусть u и v – две вершины графа G, граф Н=G-u-v. К графу Н присоединим новую вершину v1, соединив ее ребром с каждой из вершин, входящих в объединение окружений вершин u и v в графе G. Говорят, что построенный граф получается из графа G отождествлением вершин u и v. Стягивание ребра. Эта операция означает отождествление смежных вершин u и v в графе G. На рис. 18 показаны граф G, и граф полученный из G стягиванием ребра {1,2}.
Рис. 18 Граф G называется стягиваемым к графу Н, если Н получается из G в результате некоторой последовательности стягивания ребер. Очевидно, что любой непустой связанный граф, отличный от К1, стягиваем к К2. Но уже не любой
14
связный граф стягивается к графу К3. Например, граф называемый простой цепью Р4, не стягивается к графу К3. Расщепление вершины – операция двойственная к операции стягивания ребра. Пусть v – одна из вершин графа G. Разобьем ее окружение произвольным образом на две части M и N и выполним следующее преобразование графа G: удалим вершину v вместе с инцидентными ей ребрами, добавим новые вершины u и w и соединяющее их ребро uw, вершину u соединим ребром с каждой вершиной из множества М, а вершину w- с каждой вершиной из множества N. Полученный граф обозначим символом G. Будем говорить, что G получается из графа G расщеплением вершины v (рис. 19).
Рис. 19
Операция удаления ребра. Эта операция позволяет обнаружить важные закономерности, свойственные графам. При удалении ребра (u, v) из графа G получается граф с теми же вершинами, что и граф G, и всеми ребрами, кроме ребра (u, v). (рис. 20)
Рис. 20
3. Маршруты, циклы и связность. Одно из наиболее простых свойств, которым может обладать граф, это свойство быть связным. Рассмотрим основные структурные свойства связных и несвязных графов. Маршрутом, соединяющим вершины v1 и vL+1 называется чередующаяся последовательность v1, e1, v2, e2, v3, e3, …, eL, vL+1 вершин и ребер графа, такая что еi=viхvi+1 (i=1,…,L). Эта последовательность начинается и кончается вершиной, и каждое ребро последовательности инцидентно двум вершинам, одна из которых непосредственно предшествует ему, а другая непосредственно следует за ним. Очевидно, что (v1 и vL+1) – маршрут можно задать последовательностью v1, v2,…,
15
vL+1 его вершин (наличие ребер подразумевается), а также последовательностью е1, е2,…, еL ребер. Маршрут называется цепью, если все его ребра различны, и простой цепью, если все его вершины (а, следовательно, и ребра), кроме, возможно, крайних, различны. Маршрут называется циклическим, если v1=vL+1 (замкнутый маршрут). Циклическая цепь называется циклом, а циклическая, простая цепь – простым циклом (все его n вершин различны). Число n ребер в маршруте (v1, vn+1) называется его длиной. Простой цикл длины n называется n-циклом, 3-цикл часто называется треугольником. Длина всякого простого цикла не менее трех, поскольку в таком графе нет петель и кратных ребер. Минимальная из длин циклов графа называется его обхватом, обозначается g(G). Окружение графа G (обозначается с(G)) – длина самого длинного простого цикла графа G. Эти понятия не определены, если в G нет циклов. Очевидно, что любую цепь графа можно рассматривать как его подграф. Рассмотрим некоторую цепь Р вида v1, v2,…, vL+1 графе G, vi и vj – входящие в нее вершины (i<j). Очевидно, что часть vi, vi+1,…, vj цепи Р, начинающаяся в вершине vi и заканчивающаяся в vj сама является цепью графа G и называется (vi, vj) – подцепью цепи Р.
Рис. 21 Для графа G, изображенного на рис. 21маршруты (1,2) и (1,2,4,7) являются простыми цепями; (1,2,4,7,8,4) – цепь не являющаяся простой; (1,2,4,7,8,4,2) – маршрут не являющийся цепью; (1,2,4,1) – простой цикл. Обхват этого графа g(G)=3. Для ориентированного графа вводится, аналогичным образом, понятие ориентированного маршрута. Аналогом цепи в этом случае служит путь (ориентированная цепь). Вершина v называется достижимой из вершин u, если существует (u, v) – путь. Контур – это конечный путь, у которого начальная и конечная вершины совпадают. При этом контур называется элементарным, если все его вершины различны (за исключением начальной и конечной, которые совпадают). Контур единичной длины, образованный дугой вида (а, а), называется петлей. Петля связывает точку саму с собой. Замечание. Понятия ребра, цепи и цикла отличаются от понятия дуги, пути и контура только тем, что для последних принимается во внимание ориентация (направление). С понятием неориентированного графа связана важная характеристика, называемая связностью графа. Граф называется связным, если любые две его несовпадающие вершины соединены маршрутом (цепью или простой цепью). В силу того, что при u ≠ v произвольный (u, v) – маршрут, не являющийся простой цепью, после устранения «лишних кусков», превращается в простую (u, v)цепь, то верны следующие утверждения.
16
Утверждение 1. При u ≠ v всякий (u, v)-маршрут содержит простую (u, v)-цепь. Утверждение 2. Всякий цикл содержит простой цикл. Справедливы также: Утверждение 3. Объединение двух несовпадающих простых (u, v)-цепей содержит простой цикл. Утверждение 4. Если С и Д – два несовпадающих простых цикла, имеющих общее ребро е, то граф (С ∪ Д) – е также содержит простой цикл. Для связанный графов очевидно следующее. Утверждение 5. Для связности графа необходимо и достаточно, чтобы в нем для какой-либо фиксированной вершины u и каждой другой вершины v существовал (u, v)-маршрут. Всякий максимальный связный подграф графа G называется связной компонентой (или просто компонентой) графа G. В этом понятии слово максимальный означает максимальный относительно включения, т.е. не содержащийся в связном подграфе с большим числом элементов. Множество вершин связной компоненты называется областью связности графа. Справедливо утверждение: каждый граф представляется в виде дизъюнктного объединения своих связных компонент. Разложение графа на связные компоненты определено однозначно. Некоторые проблемы (например, проблема изоморфизма) сводятся к случаю связных графов с помощью Утверждение 6. Для любого графа либо он сам, либо его дополнение является связным. Полезно также: Утверждение 7. Пусть G – связный граф, е∈ ЕG. Тогда: 1) если ребро е принадлежит какому-либо циклу графа G, то граф G-е связен; 2) если ребро е не входит ни в какой цикл, то граф G-е имеет ровно две компоненты. Обозначим через m(G) число ребер графа G, а К(G) – число его компонент. Возникает вопрос: сколько ребер может быть в графе порядка n с фиксированным числом К компонент. Ответ дает следующая теорема. Теорема.Если К(G)=к для n-вершинного графа G, то n-k ≤ m(G) ≤ (n-k)(n-k+1)/2, причем обе эти оценки для m(G) достижимы.
4. Характеристики графов. Рассмотрим некоторые важнейшие характеристики графов, полезные для их приложений, так как решение многих технических задач методами теории графов сводится к определению тех или иных характеристик графов. Циклическое число. Пусть G – неориентированный граф, имеющий n вершин, m ребер и r компонент связности. Циклическим числом графа G называют число ν =m-n+r Физический смысл этого числа заключается в том, что оно равно наибольшему числу независимых циклов в графе. При расчете электрических цепей цикломатическое число используется для определения числа независимых контуров.
17
Хроматическое число. Пусть р – натуральное число. Граф G называют рхроматическим, если его вершины можно раскрасить р различными цветами так, чтобы никакие две смежные вершины не были раскрашены одинаково. Наименьшее число р, при котором граф является р-хроматическим, называют хроматическим числом графа и обозначают γ (G). Если γ (G)=2, то граф называют бихроматическим. Необходимым и достаточным условием бихроматичности графа является отсутствие в нем циклов нечетной длины. Хроматическое число играет важную роль при решении задачи наиболее экономичного использования ячеек памяти при программировании. За исключением случая бихроматического графа, определение хроматического числа представляет собой довольно трудную задачу. Множество внутренней устойчивости. Множество S ⊆ V графа G=(V, E) называют внутренне устойчивым, если никакие две вершины из S несмежны, т.е. для любых u, v∈ S имеет место (u, v)∉ Е. Множество внутренней устойчивости, содержащее наибольшее число элементов, называют наибольшим внутренне устойчивым множеством, а число элементов этого множества – числом внутренней устойчивости графа G. Наибольшее внутреннее устойчивое множество играет важную роль в теории связи. Множество внешней устойчивости. Множество Т ⊂ V графа G=(V,E) называют внешне устойчивым, если любая вершина не принадлежащая Т, соединена дугами с вершинами из Т. Множество внешней устойчивости, содержащее наименьшее число элементов называют наименьшим внешне устойчивым множеством, а число элементов этого множества – числом внешней устойчивости графа G. Пример. Задача о пяти ферзях. Сколько ферзей достаточно расставить на шахматной доске так, чтобы каждая клетка доски находилась под ударом хотя бы одного из них? Эта задача сводится к отысканию наименьшего внешне устойчивого множества в графе с 64 вершинами (клетки доски), у которого (u, v)∈ Т тогда и только тогда, когда клетки u и v расположены на одной и той же горизонтали, вертикали или диагонали. Число внешней устойчивости β =5 для ферзей, β =8 для ладей, β =12 для коней, β =8 для слонов. Задача о восьми ферзях, которые нужно расставить на шахматной доске так, чтобы ни один из них не находился под ударом другого, сводится к нахождению наибольшего внутренне устойчивого множества, графа из предыдущей задачи. Существуют алгоритмы нахождения внутренне устойчивого множества и наименьшего внешне устойчивого множества (см. К.Берж. Теория графов и ее применения. М. 1962).
5. Представление графов с помощью матриц. Информация, содержащаяся в некотором графе, может быть представлена в иной, алгебраической форме посредством матриц. Эта связь графа и матрицы имеет важное значение при практическом приложении топологических методов к математическому описанию сложных систем, так как позволяет перевести
18
структурные особенности системы на язык чисел, фигурирующих в математических уравнениях. С каждым помеченным графом связаны несколько матриц, которые часто удается использовать при выявлении определенных свойств графа. Матрица смежности. Матрицей смежности А=(аij) помеченного графа G с n вершинами называется матрица порядка (nxn) с элементами ⎧1, если вершины i и j смежны, аij= ⎨ ⎩0, в противном случае Это симметрическая матрица с нулями по диагонали, в которой число единиц в стоке (сумма элементов матрицы А(G) по строкам) равно степени соответствующей вершины. Очевидно, что существует взаимно однозначное соответствие между помеченными графами с n вершинами и симметрическими бинарными (nхn) матрицами с нулями на диагонали. Бинарной называют матрицу, каждый элемент которой равен 0 или 1.
Рис. 22. Помеченный граф и его матрица смежности. Аналогично определяются матрицы смежности А мульти- и псевдографов: аij равно числу ребер, соединяющих вершины i и j (при этом петля означает два ребра). Также определяется матрица смежности А(G) ориентированного графа G: ⎧1, если дуга v i v j принадлежит G , аij= ⎨ ⎩0, в противном случае Очевидно, что любая квадратная бинарная матрица является матрицей смежности некоторого ориентированного графа.
Рис. 23. Ориентированный граф и его матрица смежности. Абстрактный граф приводит к различным матрицам смежности в зависимости от нумерации вершин. Пусть G и Н помеченные графы порядка (nxn) и G ≅ Н, т.е. G и Н различаются только нумерацией вершин, т.е. существует подстановка S на множестве вершин, сохраняющая смежность: вершины u и v тогда и только тогда смежны в G, когда их образы S(u) и S(v) смежны в Н. Следовательно, графы изоморфны тогда и только тогда, когда их матрицы смежности получаются друг из
19
друга одинаковыми перестановками строк и столбцов. Это утверждение справедливо также для мультиграфов, псевдографов и ориентированных графов. Из предыдущего утверждения вытекает, что ранги матриц смежности изоморфных графов равны, что позволяет ввести для абстрактного графа следующее определение: рангом графа называется граф его матрицы смежности. Обозначать его будем через rang G. Пусть S – произвольная подстановка, действующая на множестве {1,2,…,n}. Определим бинарную nxn матрицу S, положив ⎧⎪1, если S( j) = i, Sij= ⎨0, в противном случае ⎪⎩ Очевидно, что в каждой строке и в каждом столбце матрицы S содержится ровно по одной единице и det S= ± 1. С помощью прямых вычислений проверяется, что B=SAS-1. Это означает, что матрицы смежности изоморфных графов подобны, поэтому равны характеристические полиномы этих матриц. Следовательно, корректно определение характеристического полинома графа как характеристического полинома его матрицы смежности. Спектр этой матрицы, т.е. совокупность корней характеристического полинома с учетом их кратностей, называется спектром графа.
Рис. 24. Псевдограф и его матрица смежности. Для взвешенного графа, не содержащего кратных ребер, матрицу смежности можно определить, положив, что каждый ее ненулевой элемент равняется весу соответствующего ребра и дуги. Обратно, каждая квадратная матрица n-го порядка может быть представлена орграфом с n вершинами, дуги которого соединяют смежные вершины и имеют веса, равные соответствующим элементам матрицы. Если матрица симметрична, то она представима неориентированным графом.
Матрица инцидентности. Другой матрицей, связанной графом G, в котором помечены и вершины и ребра, является матрица инцидентности. Пусть G – (n, m) – граф, множество вершин VG={1,2,…, n} графа G, EG={e1, e2,…, em} – множество его ребер. Матрицей инцидентности помеченного графа G называется бинарная nхm – матрица J=J(G), элементы которой определяются условиями: ⎧1, если вершина k и ребро е l инцидентны, Jkl= ⎨ ⎩0, в противном случае
20
В каждом ее столбце ровно две единицы, равный столбцов нет.
Рис. 25. Граф и его матрица смежности А и матрица инцидентности J. Как и матрица смежности, матрица инцидентности определяет граф G с точностью до изоморфизма. Для ориентированных графов определение матрицы инцидентности J видоизменяется: ⎧1, если вершина k является началом дуги е l , Jkl= ⎪⎨− 1, если вершина k является концом дуги е l , ⎪ ⎩0, если вершина k и дуга е l не инцидентны.
Рис. 26. Орграф и его матрица инцидентности. Каждый столбец матрицы инцидентности содержит обязательно два единичных элемента (для орграфа эти элементы всегда имеют различные знаки и равны соответственно 1 и –1). Количество единиц в строке равно степени соответствующей вершины (для орграфа количество положительных единиц определяет положительную степень, а количество отрицательных единиц – отрицательную степень). Нулевая строка соответствует изолированной вершине, а нулевой столбец – петле, при этом с какой вершиной эта петля связана, указаний нет.
6. Деревья. Существует простой и важный тип графов, называемых деревья. С одной стороны, это достаточно просто устроенные графы, и многие задачи, сложные в общей ситуации, легко решаются для деревьев. Доказано, например, что все деревья реконструируемы; несложно распознается изоморфизм деревьев. С другой стороны, деревья находят приложения в различных областях знания. Деревом называется связный граф, не содержащий циклов. Любой несвязный граф без циклов называется ациклическим или лесом. Таким образом, компонентами леса являются деревья. Удобно считать, что граф, состоящий из одной изолированной вершины, тоже является деревом. Деревья считаются
21
существенно различными, если они не изоморфны. На рис. 27 показаны все возможные различные деревья с шестью вершинами.
Рис. 27 С увеличением числа вершин количество различных деревьев резко возрастает (например, при n=20 их насчитывается около миллиона). Среди рзличных деревьев выделяются два частных случая: последовательное дерево, представляющее собой простую цепь, и звездное дерево, в котором одна из вершин (центр) смежна со всеми остальными вершинами. Рассматриваются также деревья с ориентированными ребрами (дугами). Ориентированное дерево называется прадеревом с корнем v0, если существует путь между вершиной v0 и любой другой его вершиной (рис. 28).
Рис. 28
Рис. 29. Исходный граф (а) и два возможных дерева (б и в). Для графа G с n вершинами и m ребрами следующие утверждения эквивалентны: 1) G – дерево; 2) G – связный граф и m=n-1; 3) G – ациклический граф и m=n-1; 4) Любые две несовпадающие вершины графа G соединяет единственная простая цепь; 5) G – ациклический граф, обладающий тем свойством, что если какую-либо пару его несмежных вершин соединить ребром, то полученный граф будет содержать ровно один цикл. Из этих утверждений следует, что в любом дереве порядка n ≥ 2 имеется не менее двух концевых вершин.
22
Важное значение имеет такая точка зрения, когда деревья или лес являются частями некоторого графа, т.е. образуются из его ребер. Любая связная совокупность ребер, не содержащая контуров, вместе с инцидентными им вершинами образует дерево графа. Если такое дерево является суграфом (содержит все вершины графа), то оно называется остовом (каркасом) графа G. Очевидно, что в каждом графе существует остов: разрушая в каждой компоненте циклы, т.е. удаляя лишние ребра, придем к остову. Так как петля представляет собой простейший цикл, состоящий из одного ребра, то она не может входить в состав любого дерева графа. Ребра графа, которые принадлежат его дереву, называют его ветвями. Несложно показать, что число ребер произвольного графа G, которые необходимо удалить для получения остова, не зависит от последовательности их удаления и равно m(G)-|G|+k(G), где m(G) – число ребер, k(G) – число компонент графа G.
Рис. 30.Дерево как часть графа, а – исходный граф, б – дерево, в – остов. Выше было определено цикломатическое число графа G: ν (G)=m(G)-|G|+k(G) Справедливы утверждения: 1) Граф G является лесом тогда и только тогда, когда ν (G)=0; 2) Граф G имеет единственный цикл тогда и только тогда, когда ν (G)=1; 3) Граф, в котором число ребер не меньше, чем число вершин, содержит цикл. Остов минимального веса. Рассмотрим задачу, возникающую при проектировании линий электропередачи, трубопроводов, дорог и т.п., когда требуется заданные центры соединить некоторой системой каналов связи так, чтобы любые два центра были связаны либо непосредственно соединяющим их каналом, либо через другие центры и каналы, и чтобы общая длина (или, например, стоимость) каналов связи была минимальной. В этой ситуации заданные центры можно считать вершинами полного графа с весами ребер, равными длинам (стоимости) соединяющих эти центры каналов. Тогда искомая сеть будет кратчайшим остовным подграфом полного графа. Очевидно, что этот кратчайший остовный подграф должен быть деревом. Решение этой задачи простым перебором вариантов потребовало бы чрезвычайно больших вычислений даже при относительно малых n, поскольку полный граф Кn содержит nn-2 различных остовных деревьев. Однако имеются эффективные алгоритмы ее решения. Опишем алгоритмы Дж. Краскала и Р. Прима применимые к произвольному связному графу. Задача. В связном взвешенном графе G порядка n найти остов минимального веса. Алгоритм Краскала, решающий эту задачу, заключается в следующем.
23
1. Строим граф Т1=Оn+е1, присоединяя к пустому графу Оn на множестве вершин VG ребро е1∈ EG минимального веса. 2. Если граф Тi уже построен и i