Graphs(수정)

Download Report

Transcript Graphs(수정)

C
c
d
A
kneiphof
a
g
e
D
f
B
1
10
5
0
6
13
1
2
8
7
3
5
2
4
4
6
9
6
6
Graphs

The Graph Abstract Data Type

Elementary Graph Operations

Minimum Cost Spanning Trees

Shortest Path And Transitive Closure

Activity Networks

Koenigsberg bridge problem

어떤 지점에서 시작하여 각 다리들을 모두 꼭 한 번씩 만 건너면서 시작지점으로
돌아올 수 있는가?
C
d
c
A
kneiphof
a
B
e
C
g
D
b
c
A
a
f
g
d
e
D
b
f
B
(b)
(a)
The bridge of Koenigsberg
 Euler’s solution
• 각 지점을 vertex로 각 다리를 edge 로 나타내어 문제를 graph로 표현
• vertex의 degree를 그 vertex에 붙어있는 (incident on) edge의 수로 정의
• 필요 충분 조건 :모든 vertex의 degree가 짝수
• 문제가 성립하는 경우를 Eulerian walk 라고 이름함

Definitions
A
graph G = (V,E)
where, V: a finite, nonempty set vertices, denoted V(G)
E: a finite, possibly empty set of edges, denoted E(G)
A
undirected graph : edge를 나타내는 vertex 쌍에 순서가 없는
A
directed graph : edge를 나타내는 vertex 쌍에 순서가 있는 경
경우
우
(digraph) < v0 ,v1 >에서 v0 는 tail, v1 은 head
Definition of Graph
0
1
0
2
3
0
1
3
2
4
5
1
6
G2
G1
2
G3
Three sample graphs
* sample graph의 set representation:
V(G1)={0,1,2,3}
V(G2)={0,1,2,3,4,5,6}
V(G3)={0,1,2}
E(G1)={(0,1), (0,2), (0,3), (1,2), (1,3), (2,3)}
E(G2)={(0,1), (0,2), (1,3), (1,4), (2,5), (3,6)}
E(G3)={<0,1>, <1,0>, <1,2>}
* tree는 graph의 특수한 경우(예를 들어 G2)
 Restrictions on our graphs:
 한 vertex i로 부터 자신에게 돌아가는 self loops로 불리우는 edge는 존
재할 수 없음. 즉 edge(vi,vi) 또는<vi,vi >는 존재할 수 없음
 같은 edge가 여러 번 존재할 수 없음. 이 제한이 없는 경우를
multigraph라 이름함.
 A complete graph
 최대 개수의 edge를 가지는 graph
 n개의 vertex를 가지는 undirected graph의 경우, 이 숫자는 n(n-1)/2.
 n개의 vertex를 가지는 direct graph의 경우, 이 숫자는 n(n-1).
 예를 들어, G1은 vertex가 네 개인 complete graph임.
 (v0,v1)이 undirectd graph의 한 edge일 경우 vertex v0와 v1은
adjacent하고, edeg(v0, v1)은 vertex v0와 v1에 incident on하다

<v0,v1>이 directed graph 의 한 edge일 경우 vertex v0는 vertex v1에 adjacent
to 하고 v1은 v0에 adjacent from하다. Edge<v0,v1>은 vertex v0와 v1에
incident on 하다

G의 subgraph G’: V(G)  V(G’), E(G)  E(G’)인 성질을 가지는 graph

Graph G에서 vertex vp에서 vertex vq 로 가는 path 는 (vp,vi1),(vp,vi2),…..,(vin,vq)
들을 undirected graph 의 edge들이라 할 때 vp,vi1,vi2,…, vin,vq의 vertex
sequence 이다. 여기서 (vp,vi1),(vp,vi2),…,(vin,vq)는 undirected graph의 edge들
이다. G’가 directed graph라면, path는 <vp,vi1>,< vp,vi2>,…..,<vin,vq>로 이루어
진다. Path의 length는 path내의 edge의 갯수이다.

Simple path는 처음과 끝의 vertex를 제외하고는 path내의vertex가 서로 다
른 path이다. graph G3에서 0,1,2는 simple directed path이다.처음과 끝의
vertex가 같은 simple path를 cycle이라 한다.
 Undirected graph G에서, 두 vertex v 와 v 사이에 path가 존재할 경우
0
1
v0와v1은 connected되었다고 한다. undirected graph G의 모든 vertex
쌍 vi,vj (ij)에 vi에서 vj로 가는path가 존재할 경우 undirected graph는
connected 되었다고 한다. (예 : G4는 connected되어 있지 않다)
0 H1
1
2
3
H2
4
5
6
7
A graph with two connected components (G4)
 Undirected graph 의 connected component (또는 간단히 component)
는 maximal connected subgraph를 의미한다.

Tree는 connected 이고 acyclic한 (cycle이 없는)graph이다.

Directed graph에서 V(G)의 모든 vertex쌍 vi,vj에 대하여 vi에서vj로 , vj에서
vi로의 directed path 가 존재할 경우 directed graph는 strongly connected되
어 있다고 한다. Strongly connected component는 strongly connected 되어
있는 maximal subgraph이다.

Undirected graph 에서 vertex의 degree는 그 vertex에 incident to한 edge들
의 숫자이다.

directed graph에서 vertex v의 in-degree는 v를 head로 하는 edge의 숫자이
며, out-degree는 v를 tail로 하는 edge의 숫자이다.

N개의 vertex 와 e개의 edge를 가지는 graph G에서 di가 vertex i의 degree라
면,edge의 개수는:

(  d )/2
n-1
i
i=0
앞으로, directed graph는 digraph, undirected graph는 graph라 이름한다.
ADT Graph
objects: 공집합이 아닌 정점의 집합과 무방향 간선의 집합으로 각 간선은 정점의 쌍이다.
functions:
for all graph ∈ Graph, v, v1, and v2 ∈ Vertices
Graph Create()
::= return an empty graph
Graph InsertVertex(graph, v)
::= return a graph with v inserted
v has no incident edges
Graph InsertEdge(graph, v1, v2) ::= return a graph with a new edge
between v1 and v2
Graph DeleteVertex(graph, v)
::= return a graph in which v and all edges
incident to it are removed
Graph DeleteEdge(graph, v1, v2) ::= return a graph in which the edge(v1, v2) is removed
Leave the incident nodes in the graph
Boolean IsEmpty(graph)
::= if(graph = = empty graph) return TRUE
else return FALSE
List Adjacent(graph, v)
::= return a list of all vertices that are adjacent to v

Graph Representations
1. adjacency matrix
2. adjacency list
3. adjacency multilist

adjacency matrix

G의 adjacency matrix는 2차원 n * n 배열이다.이를 adj_mat라고 이름한다.
edge(vi,vj)(digraph의 경우는 <vi,vj>)가 E(G)에 존재하면 adj_mat[ i ][ j ]=1,아니면
adj_mat[ i ][ j ]=0으로 표현함.
01 2 3 4 5 6 7
0123
0
01100000
0
0111
1
10010000
G1 12 11 01 10 11
2
10010000
3
01100000
3
1110
G4 4
00000100
012
5
00001010
0
6
G3 1 01 01 10
00000101
7
00000010
2
000
Adjacency matrices for G1, G3,and G4

Undirected graph 의 adjacency matrix는 symmetric하다.즉, matrix
의 upper 또는 lower triangle만으로 표현가능. digraph의 adjacency
matrix는 symmetric 하지는 않다.
 Undirected graph에서 어떤 vertex i의 degree는 row sum이다.
n-1
adj_mat[i][j]

j=0
directed graph에서는 row sum은 out-degree, column sum은 indegree이다.

Counting edges, determining whether the graph is connected : O( n² )
matrix에서 potentially n² - n 개(n:diagonal element)의 entry를 처리해야
하는 필요 때문임
Graph Representations
 Adjacency Lists
 adjacency matrix의 n개의 row대신에 각 vertex별로 하나씩 모두 n개
의 linked list를 사용
headnodes
headnodes
0
1
G1
2
3
1
0
0
0
0
1
2
1
G3
0
null
2
2
1
1
2 null
3
3
3
2
null
null
null
null
0
1
2
3
G4 4
5
6
7
Adjacency list for G1,G3 and G4
1
0
0
1
5
4
5
6
2 null
3 null
3 null
2 null
null
6 null
7 null
null
 n 개의 vertex와 e 개의 edge를 가지는 undirected graph에서


adjacency list를 사용하는 표현하는 방법은 n개의 head nodes와 2e
개의 list nodes를 가진다.
List내의 node들의 순서에는 제한이 존재하지 않는다.
The C declaration for adjacency list representation
#define MAX_VERTICES 50 /*maximum number of vertices*/
typedef struct node *node-pointer;
typedef struct node
{
int vertex;
struct node *link;
};
node-pointer graph[MAX_VERTICES];
int n=0;
/*vertices currently in use*/
 Adjacency list의 node를 순차적으로(sequentially)배열
하여 pointer를 사용하지 않는 방법도 고려
 Undirected Graph의 경우:
- vertex의 degree는 그 vertex의adjacency list 내의 node수를 셈으
로써 가능
- G의 edge 총 개수를 counting하는 시간:O(n+e)
(여기서, n:graph G 의 vertex 개수, e:graph G의 edge 개수)
 Directed Graph의 경우:
- vertex의 out-degree는 그 vertex의 adjacency list내의 node 개수
를 셈으로써 가능
- G의 edge 총 개수를 counting 하는 시간:O(n+e)
 Directed Graph의 경우, vertex의 in-degree를 구하는 데이터 구조
• inverse adjacency list 사용방법
: inverse adjacency list는 adjacency list 의 경우와는 달리 각 vertex 별로 그
vertex에 adjacent to 한vertex들에 대한 node들을 가짐
• node 구조를 변경하는 방법
- node는 네 field(tail, head, column link for head, row link for tail)를 가지며 하나 edge를 표현함
- headnodes의 column link를 따라서 list내의 node수를 counting 하면 in-degree를 구할 수 있다
- headnodes의 row link를 따라서 list 내의 node수를 counting 하면out-degree를 구할 수 있다
Graph Representations
row
Headnodes
(shown twice)
column
0
1
0
0
1
2
1
NULL
tail
0
1
2
NULL NULL
NULL
head
Orthogonal representation of graph G3
1
2
NULL NULL
 Adjacency multilists
 하나의 edge당 하나의 node가 사용되며 이들이 여러 list에서 공유
되는 표현방법
 adjacency list는 vertex의 방문 여부를 표현하기에 어려운 구조임
 adjacency multilist에는 하나의 edge당 하나의 node가 존재하므로 방
문한 edge는 marked필드를 이용하여 방문했음을 표현 가능함

C declarations for the node structure :
typedef struct edge *edge_pointer;
typedef struct edge {
short int marked;
int vertex1;
int vertex2;
edge_pointer path1;
edge_pointer path2;
};
edge_pointer graph[MAX_VERTICES];
0
1
2
headnodes
N1
0
0
1
N2
N4
edge (0, 1)
1
N2
0
2
N3
N4 edge (0, 2)
2
N3
0
3
NULL
N5 edge (0, 3)
3
N4
1
2
N5
N6 edge (1, 2)
N5
1
3
NULL
N6 edge (1, 3)
N6
2
3
NULL NULL
3
The list are :
G1
vertex 0 : N1N2N3
vertex 1 : N1N4N5
vertex 2 : N2N4N5
vertex 3 : N3N5N6
edge (2, 3)
Adjacency multilists for G1

Weighted edges



adjacency matrix의 경우에는 matrix의 각 position에 weighted value를 사용
adjacency list나 adjacency multilist의 경우에는 node구조에 weight field추가
weighted edge를 가지는 graph를 network라 한다.
0
1
2
3
G1

Problem
Undirected graph G = (V,E)와 하나의 vertex v  V(G)가 주어졌을 때, v에서
도달할 수 있는 모든 vertex를 방문한다.



depth first search(DFS) : preorder tree traversal과 유사
breath first search(BFS) : level order tree traversal 과 유사
Depth First Search
1. start vertex v 를 방문
2. v의 adjacency list에서 방문하지 않은 vertex w를 선택하여 w에 대하여 depth first
search를 수행 (recursion이용)
 Breadth First Search
1. vertex v에서 시작하여 v의 adjacency list에 있는 모든 vertex들을 방문하고, 방문한 vertex는 모두
queue에 넣고 방문했음을 표시함.
2. queue에서 vertex하나를 끄집어내어 이vertex의 adjacency list에서 방문하지 않은 모든 vertex들
을 방문한다. queue가 모두 빌 때까지 이 과정을 계속한다.
DFS and BFS

DFS
1. 시작정점 v를 방문하고 mark한다.
2. V에 인접하면서 방문하지 않은 w정점을 선택하여 w를 중심으로 DFS를 적용한다.
3. 만약, 모든 인접한 정점들이 이미 방문된 정점v를 만나면, 방문하지 않은 인접한 정
점 w를 가지고 있으면서 최종적으로 방문되었던 정점으로 거슬러 올라가 DFS 시
작한다.
4. 방문한 어떠한 정점으로 부터 방문되지 않은 정점에 도달할 수 없을 떄 종료한다.

BFS
1. 시작정점 v를 방문하고 mark한다.
2. V에 인접한 방문하지 않은 정점들을 방문하고 mark한다.
Let, w, x, y, z : v에 인접하면서 방문한 정점들
3. 이들 정점을 중심으로 BFS를 적용한다.
4. DFS의 4.와 동일
DFS and BFS

Digraph : start vertex 1


DFS : 1, 2, 3, 8, 7, 9, 5, 6
BFS : 1, 2, 6, 3, 7, 5, 9, 8
1
2
7
6
9
5
8
3
4
•DFS, BFS는 G의 adjacency list에 의존하지만, starting이 되면 계속 같은 과정을 반복
BFS 프로그램
DFS 프로그램
typedef struct queue *queue_pointer ;
#define FALSE
#define true
0
typedef struct queue {
int vertex ;
1
queue_pointer link ;
short int visited[MAX_VERTICES];
};
void dfs(int v)
void addq (queue_pointer *, queue_pointer *, int) ;
{ /* depth first search of a graph
beginning with vertex v. */
int
deleteq (pueue_pointer *);
void bfs (int v)
{/* breath first traversal of a graph, starting with node v the global
array visited is initialized to 0, the queue operations are similar
node_pointer w;
tothose described in linked lists*/
node_pointer w ;
queue_pointer front, rear ;
front = rear = NULL ;
printf (“%5d”,v) ;
visited[v] = TRUE ;
addq (&front , &rear , v) ;
while ( front )
{
v = deleted ( &front ) ;
for ( w = graph [ v ] ; w ; w = w-> link ) /* graph[ ]: headnodes */
if ( ! visited [w -> vertex] )
visited [ v ] = TRUE ;
printf ( “ %5d” , v ) ;
for ( w = graph [ v ] ; w ; w = w -> link )
/* graph [ ] : headnodes */
if ( ! visited [w -> vertex])
{
dfs ( w -> vertex);
}
}
}
}
printf ( “%5d ”, w -> vertex ) ;
addq ( &front , &rear, w ->vertex ) ;
visited [w -> vertex ] = TRUE ;
V0
V1
V3
V2
V4
V5
V6
0
1
2
1
0
3
4
NULL
2
0
5
6
NULL
3
1
7
NULL
4
1
7
NULL
2
7
NULL
2
7
NULL
3
4
5
6
V7
7
NULL
Figure 1 : Graph G and its adjacency list
1. DFS (Starting V0) ====> V0,V1,V3,V7,V4,V5,V2,V6
2. BFS (Starting V0) ====> V0,V1,V2,V3,V4,V5,V6,V7
5
6
NULL
* If G is a digraph!
V1
V3
V2
V5
V6
V7
V8
V4
* It is adjacency list!
V1
V2
V3
NULL
V2
V4
V5
NULL
V3
V6
NULL
V4
V8
NULL
V5
V7
NULL
V6
V7
NULL
V7
V8
NULL
V8
NULL
1. DFS (Starting V1) ====> V1,V2,V4,V8,V5,V7,V3,VV6
2. BFS (Starting V1) ====> V1,V2,V3,V4,V5,V6,V8,V7
* If G is a digraph!
* It is adjacency list!
V1
V3
V6
V2
V5
V4
V1
V3
V2 NULL
V2
V5
V4 NULL
V3
V6 NULL
V4
V8 NULL
V5
V7 NULL
V6
V7
V7 NULL
V7
V8
V8
V8 NULL
NULL
1. DFS (starting V1) ====> V1,V3,V6,V7,V8,V2,V5,V4
2. BFS (starting V1) ====> V1,V3,V2,V6,V5,V4,V7,V8
 Analysis of DFS
- adjacency list 를 사용하므로 O(e)
- adjacency list를 사용할 경우 각 vertex 별로 adjacent vertex들을 찾는데 O(n)
이 필요하고, n개 이하의 vertex를 방문해야 하므로 전체로는 O( n² )

Analysis of BFS
- while loop는 최대 n번 ( headnodes의 개수 ) 수행
- adjacency list의 경우 이 loop의 total cost는 d0+….+d n-1=O(e),
where di=degree(vi) (각 node 데이터 구조를 access)
- adjacency matrix표현의 경우 total time은 O(n² ) (각 vertex당 O(n) time을 요함)
Connected Components
 Problem
1. Undirected graph가 connected되어 있는가?
2. Graph의 connected components를 출력
 C 프로그램
void connected (void )
{
/* determine the connected components of a graph */
int i ;
for ( i = 0 ; i = n ; i++ )
if ( !visited [ i ] ) {
dfs ( i );
/ *dfs seardhes all the vertices in a component* /
printf ( “ \ n” ); / * “\n” 수 만큼의 component 존재 */
}
}

Analysis of connected
- adjacency list 표현의 경우 O( n+e ) (for loop : O( n ), dfs : O( n ))
- adjacency matrix표현의 경우 O( n² ) (모든 potential edge를 모두 봐야 함)
 Definition
- graph G의 모든 vertex를 포함 하고 graph G의 edge만으로 구성된 tree를 spanning
tree라 한다
- spanning tree는 dfs나 bfs를 사용하여 만들 수 있으며 , dfs로 생성되는 spanning tree
를 depth first spanning tree라 하고 , bfs로 생성되는 spanning tree를 breath first
spanning tree라 한다. (예 Figure 2는 Figure 1 graph의 spanning tree 이다.)
V0
V1
V3
V0
V2
V4 V5
V7
V1
V6
V3
V2
V4 V5
V6
V7
(a) dfs (0) spanning tree
(b) bfs (0) spanning tree
Figure 2. dfs and bfs for graph of Figure 1

Example [ Creation of circuit equations ]
- spanning tree에다 edge를 하나씩 부가하고 kirchoff의 제 2 법칙 적용
(independent cycle들을 생성)

Definition
최소 개수의 edge를 가지는 subgraph를 minimal subgraph라 한다.

Property
- graph G의 spanning tree는 V(G)=V(G’)이고 G’는 connected 되어 있는
minimal subgraph G’이다.
- n개의 vertex를 가지는 connected graph는 n-1개 이상의 edge를 가지며
n-1개의 edge를 가지는 connected된 graph는 tree이다.
그러므로, spanning tree는 minimal subgraph이다.
• minimum cost spanning tree는 communication network설계에 응용된다

Definition
- 어떤 vertex v와 이 vertex에 incident on한 모든 edge를 삭제할 때 적어도 두 개 이상의
connectd component를 가지는 graph G’가 생길 경우 이 vertex를 articulation point라 한다.
- articulation point 가 없는 connected graph를 biconnected graph라 한다.
- connected undirected graph의 biconnected component는 graph G의 maximal biconnected subgraph
H.
- 여기서, maximal biconnected graph H는 다음과 같은 성질을 갖는다. Graph G에는 biconnected 이면서 동시에 어
떤 biconnected subgraph H 를 properly contain 하는 biconnected subgraph가 존재하지 않는다.
•예 : Figure 3 (a) graph의 biconnected components는 (b) graph이고 articulation point는 1,3,5,7이다.
0
8
1
7
2
3
4
5
9
3
0
2
6
(a) Connected graph
3
4
9
8
7
1
1
5
7
5
6
(b) Biconnected components
Figure 6.19: A connected graph and its bi-connected component
7
• 한 graph의 biconnected component들은 최대 하나의 공통 vertex를 가진다
(만약, 둘이라면 둘 다 articulation point가 아니다.)
• 한 edge 는 둘 다 biconnected component 에 만 존재한다(둘에 존재 한다면
두 개 이상의 vertex를 공유함). 즉 , biconnected component들은 edge들을 partition한다.

Articulation point를 찾는 방법
• depth first spanning tree를 이용하여 articulation point를 구할 수 있다.
다음부터 이를 설명한다.
• depth first spanning tree에서 각 vertex들의 방문 순서 번호를 각 vertex의
depth first number(dfn)라 한다.depth first spanning tree에서 u가 v 의 ancestor
이면 dfn(u) < dfn(v)이다.
• 예: Figure 4 (a)는 Figure 3 (a ) graph를 dfs(3 )로 depth first search한 depth
first spanning tree이다.
Figure 4 (b)는 Figure 4 (a )를 root를 3으로 하여 다시 그린 그림이다.
점선으로 표현된 edge는 nontree edge이다.
0 0
3 1
2 2
1
4
9 8
4
3
8 9
7 7
5
5
6 6
(a ) depth first spanning tree for dfs (3)
3
0
1 4
5 5
2 2
3
1
6 6
4 0
8 9
7 7
(b)
Figure 6.20 : Depth first spanning tree of Figure 6.19(a)
• nontree edge (u,v)에서 u가 v의 ancestor이거나, v가 u 의 ancestor일
경우 (u,v)를 back edge라고 한다.
9 8
• depth first search 의 정의에 의하면 , 모든 nontree edge는 back edge이다.
(만약, 아니라면 dfs에 의해 미리 traverse되었을 것임.예를 들어,vertex 1,7사이에
edge가 있었다면 depth first spanning tree에서 vertex 7은 1 아래에 존재할 것임)
• depth first spanning tree의 root가 articulation point일 필요 충분조건은 이 vertex
가 두 개 이상의 자식을 가질 경우이다.
(모든 nontree edge는 back edge이므로 subtree간의 연결은 있을 수 없다.)
• depth first spanning tree의 root가 아닌 어떤 vertex u가 articulation point일 필요
충분 조건은, 이 vertex가 적어도 하나 이상의 자식 vertex w를 가져서, w,w의
0 or more descendents, 하나의 back edge 만으로 구성되는 path를 이용하여 u의
ancestor 에 도달할 수 없을 경우이다.
(예 : Figure 4에서 vertex 1,5,7은 이 조건을 만족한다.그리고,이들은 articulation point이다.)
• low(u)를 u에서 u의 descendents와 하나의 back edge만으로 도달할 수 있는 path의
마지막 vertex의 minimum dfn 으로 정의한다.[다음 항목 참조]
- low (u)= min{ dfn (u ),min {low(w) |w is a child of u },
min { dfn (p) | (u,p) is a back edge }}
• u 가 articulation point 일 경우 필요 충분 조건은, u가 spanning tree의 둘 이상의
자식을 가지는 root이거나,root가 아니면서 low(w)  dfn(u)인 자식 w 를 가지는
경우이다.
• 예 : Figure 4의 depth first spanning tree에 대하여 dfn과low를 구하면 다음과 같다.
vertex
0
1
2
3
4
5
6
7
8
9
dfn
4
3
2
0
1
5
6
7
9
8
low
4
0
0
0
0
5
5
5
9
8
Articulation points :
vertex 1: low(0) =4dfn(1)=3
vertex 2: low(8) =9  dfn (7) =7
vertex 5: low(6) =5  dfn (5) =5
vertex 3: root and has more than one child
A
• A graph is connected
  a path between each of vertices.
B
iff
D
• A digraph G = ( v , z ) is strongly connected
 정점 v 와 w에 대해  a path from v to w
iff
H
E
F
G
C
I
&  a path from w to v
Digraph
• A Finding Strong Components 문제 !
• 특성
1) A strongly connected component는 Digraph
상에서 Maximal strongly connected subgraph
2) v,w  V
v S w   a path from v to w
 a path from v to w
 A Strong Component는 하나의 equivalence
class를 구성
1.
B
2.
A
E
K
3.
H
F
4.
C
I
J
J
K
Strongly Connected components
 “Strong Component”
D
G
• The condensation of G
let S1 , S2 , … , Sp : strong components
the digraph G’ = (V’,E’)
where V’ has p elements
sisj  E’

 edge  E 즉,
iff
Si
Sj
Strong component
(ex) 앞의 digraph 상에서 the condensation of G
where 1, 2, 3, 4 : strong components
1
3
2
4
• network flow problem
B
4
D
5
5
C
1
9
8
3
2
A
E
“Ford-Fulkerson
Algorithm”
A에서 F까지
“석유전송을 최대로”
F

3
B
1
5
C
E
4
•planar graph : edge와 edge를 교차시키지 않고 그리는 문제

•isomorphic (동형)문제
U

isomorphic
V
W
X ~ Y ,Y ~ Z , Z ~ W
X
Z
Y
6
0
1
A
9
D
5
4
F
3
9
• weighted undirected graph 의 spanning tree의 cost는 spanning tree의edge들의 cost(weight)의 합이다.
• spanning tree중에서 최소의 cost를 가지는 것을 minimum cost spanning tree 라 한다.
• Three algorithms for the minimum cost spanning tree
- Kruskal’s, Prim’s, and Sollin’s algorithms
- 각 algorithm들은 greedy method를 이용
• Greedy method
- 각 stage 별로 어떤 criterion을 사용하여 best decision을 한다.
- 전형적인 criterion으로는 least cost, highest profit criterion이 있다.
- 각 decision은 이후에 변경될 수 없으므로 문제의 constraints을 만족하는 feasible solution을 찾는다.
(optimal solution 이 아닐 수도 있다.)
• Constraints for minimum cost spanning tree algorithms
1. graph 내의 edge만을 사용할 것.
2. 정확히 n -1개의 edge를 사용할 것.
3. cycle을 이루는 edge들을 사용하지 않을 것.
1. Kruskal’s Algorithm
- spanning tree T에 한번에 하나씩의 edge를 추가
- edge들을 cost에 대한 non-decreasing order로 정렬하여 cycle을 이루지 않는 edge를 택하여 T에 추가
- graph G는 connected되어 있고 n개의 vertex를 가지므로 n-1개의 edge만이 T에 포함됨

Formal description
T={ };
while ( T contains less than n -1 edges && E is not empty )
{
choose a least cost edge (v,w) from E ;
delete (v,w) from E ;
if ((v,w) does not create a cycle in T )
add (v,w) to T;
else
discard (v,w);
}
if ( T contains fewer than n -1 edges)
printf (“No spanning tree\n”); /*the graph is not connected*/
• graph G
1
10
5
0
6
13
1
2
8
7
5
2
4
4
6
9
6
6
3
• adjacency lists
0
1
5
2
13
3
8 null
1
0
5
2
2
4
6
5
10 null
2
0
13
1
2
3
7
4
1
3
0
8
2
7
4
4
6
6 null
4
1
6
2
1
3
4
6
9 null
5
1
10
6
6 null
6
3
6
4
9
5
6 null
null
0 28
10
1
14
16
5
24 6
2
25
4
18
12
22 3
5
6
10
10
1
5
0
0
6
2
4
1
4
3
(a)
(b)
(c)
0
0
14
6
2
4
16
2
4
3
(e)
12
4
3
(f)
12
(d)
10
16
2
4
22
12
3
1
14
6
5
2
0
10
1
14
6
5
6
0
10
1
1
5
2
3
10
5
0
3
(g)
12
1
14
6
5
25 4
22
3
(h)
16
2
12
8
1
2
2
7
3
4
9
4
10
5
12 6
6
14
7
3
8
# DFS of graph G
: 0 1 2 3 4
# BFS of graph G
6 5
:0 1 2 3 4 5 6
1
0
5
1
0
5
2
4
2
4
3
6
3
6

Minimum cost edge의 계산
- E 를 sorted sequential list로 : O( e log e)
- better method :min heap 이용
finding the next cost edge : O(log e)

Cycle checking
- union -find operation (set representation in trees)이용
- edge로 연결된 vertex들을 하나의 set으로 간주
- edge를 추가하려 할 때 edge의 양쪽 vertex들이 이미 같은 set내에 존재 하면
cycle이 됨
.

Analysis
- union find operation은 minimum cost edge 선택 algorithm(O(log e))보다
expensive
-그러므로, total computing time 은 O(e log e) (각 edge 마다 수행 되므로)

Theorem :
G : undirected connected graph 일 때, Kruskal’s algorithm은 minimum
cost spanning tree를 만든다
less
2. Prim’s algorithm
- spanning tree T에 한번에 하나 씩의 edge를 추가
- 각 stage에서 선택된 edge들은 tree를 구성(Kruskal’s algorithm의 경우는
forest구성)
- single vertex를 가지는 tree 에서 algorithm 시작
- T 에 하나 씩의 edge (u,v)를 추가하여도 역시 tree가 되는 edge(u,v)를 T에
추가 (n-1개의 edge가 T에 포함될 때까지 수행 )

Formal description
T = { } ; /* T is set of tree edges */
TV = { 0 } ; /*TV is set of tree vertices */
/* start with vertex 0 and no edges */
while ( T contains less than n -1 edges ) {
let (u ,v) or (v ,n ) be a least cost edge such that u  TV and v  TV;
if (there is no such edge )
break ;
add v to TV;
add (u , v) or (v ,u) to T ;
}
if ( T contains fewer than n -1 edges)
printf (“ No spanning tree\n”);
• TV 내의 존재하지 않는 각 vertex v 는 다음과 같은 companion vertex, near (v)를 가진다.
Cost (near (v),v)=minw[cost (w,v) ] where w  TV (만약, (v , w)  E이면, cost (v,w) = 로 가정)
n 이 vertex갯수라면, 각 stage에서 cost (near(v),v)가 최소이고 v  TV 인 vertex v를 선택
하는데 O( n² )가 필요
(각 v 마다 near (v)를 찾는데 O( n ), v 가 최대 n개 이므로)
0
0
10
1
5
10
2
25
4
0 28
10
1
14
16
5
24 6
2
25
4
18
12
22 3
10
5
25
6
2
4
3
(a)
(b)
0
0
1
5
4
12
3
(d)
25
25
6
2
4
22
3
(c)
1
6
4
22
1
0
10
2
10
5
3
6
22
1
5
6
0
10
16
5
2
25
12
3
(e)
Prim 알고리즘의 진행 단계
14
6
16
2
4
22
1
12
3
(f)
8
1
2
2
7
3
4
9
4
10
5
12 6
6
14
7
3
8
3. Sollin’s Algorithm
- spanning tree T 에 한번에 여러 개의 edge들을 추가
- 각 stage 에서는 graph 의 모든 vertex 와 선택된 edge들로써 spanning forest를 구성
- 한 stage 동안 forest내의 각 tree를 유지하는 minimum cost edge를 선택
- forest내의 두 tree가 같은 edge를 선택할 수 있으므로 edge의 multiple copies를 제거할
필요가 있음
- 처음은 edge가 없는 n개의 tree로부터 시작함
- stage의 종료 시점에 하나의 tree만이 존재하든지 선택될 edge가 남지 않을 경우 수행
을 종료함
0
0 28
10
1
14
16
5
24 6
2
25
4
18
12
22 3
10
5
0
14
6
10
5
2
4
22
1
12
3
(a)
- 각 vertext에서 edge 선택
(0,5)
(1,6)
(2,3)
(3,2)
(4,3)
(5,0)
(6,1)
25
14
6
16
2
4
22
1
12
3
(b)
8
1
2
2
7
3
4
9
4
10
5
12 6
6
14
1
7
3
2
2
8
- 각 vertext에서 edge 선택
(1,2)
(2,1)
(3,4)
(4,3)
(5,6)
(6,5)
(7,8)
(8,7)
3
4
5
6
7
3
4
6
8

Problem
1. source A에서 destination B로 가는 path가 있는가 ?
2. 여러 개가 있을 경우 shortest path는 ?
• 각 edge에는 weight(distance)가 존재하며 보통 weight는 양수이다.
• path의 length 란 그 path에 존재하는 모든 edge의 weight의 합을 의미한다.
• one street의 경우는 directed graph로 표현 가능하다.

종류


Single Source All Destination


Dijkstra’s algorithm
Bellman-Ford algorithm
All Pairs Shortest Paths


위의 반복적용
Floyd-Warshall algorithm

Problem
directed graph G=(V,E)의 모든 edge에 대한 weighting function w(e) ( >0 )
주어졌을 때, source vertex v0로부터 G의 나머지 vertex각각에 대한
shortest path를 구함
45
50
v0
20
10
v2
15
10
v1
20
15 v3
v4
35
3
30
v5
Path
length
1) v0 v2
10
2) v0 v2 v3
25
3) v0 v2 v3 v1 45
4) v0 v4
45
Graph and its paths from v0
 Greedy algorithm
- S : shortest path가 계산된 vertex들의 집합 (v0포함)
- S에 존재하지 않는 vertex w에 대하여, distance[w]란 v0에서 시작하여 S내의 vertex만을 거쳐서
w로 끝나는 shortest path length로 정의한다.
- shortest path들을 path length의 nondecreasing order순으로 계산할 경우다음과 같은 성질이 존재한다.
1. 다음에 계산할 shortest path가 vertex u로 끝나는 path라면, v0에서 u로 가는 path는 S내의 vertex만을 지난다.
2. S에 존재하지 않는 vertex들 중에서 최소의 distance[u]를 가지는 vertex u가 선택된다.[1번 성질에 의하여
length대신 distance를 사용]
3. v0에서 u로 가는 shortest path가 계산된 후, u는 S에 속한다. S에u를 추가하면 distance [w](wS)는 변경될 수
있으며, 변경된다면 변경된 path의 length는 distance[u]+length(u,w)가 된다.
 Dijkstra’s algorithm
- n개의 vertex들은 0에서 n-1까지로 번호가 매겨져 있다고 가정
- 집합 S를 유지하기 위하여 found[n]을 이용 (S에 vertex i가 존재하면 found[ i ] 는
TRUE, 아니면 FALSE)
- graph는 cost adjacency matrix, cost[n][n]으로 표현
- G에 edge i,j가 존재하지 않으면 cost [ i ][ j ]는 cost matrix내의 어떤
값보다 크고 ( all edges weight (edge)보다 큰), distance[u]+length(u,w)
가 overflow를 일으키지 않는 어떤 큰 값으로 지정함

동적 프로그래밍 방법
: 모든 u에 대해 distn-1[u]를 구함

distk[u] = min{distk-1[u], min_i{distk-1[i] + length[i][u]}}
Boston
4
1500
Chicago
1200
San Francisco
800
1
3
250
2
1000
Denver
300
5
1000
New York
1400
0
1700
7
Los Angeles
900
New Orleans
1000
6
Miami
(a) 방향 그래프
선택된
정점
반복
거 리
LA
SF
DEN
CHI
BOST
NY
MIA
NO
[3]
[4]
[5]
[6]
[7]
[0]
[1]
[2]
----



1500
0
250


1
5



1250
0
250
1150
1650
2
6



1250
0
250
1150
1650
3
3


2450
1250
0
250
1150
1650
4
7
3350

2450
1250
0
250
1150
1650
5
2
3350
3250
2450
1250
0
250
1150
1650
6
1
3350
3250
2450
1250
0
250
1150
1650
초기

0
3
4

10

7
2
5
6

1
4
10
2
2
6

9

3
S ={0}
distance[] = 0 7   3 10 
S={0, 4}
distance[] = 0 5  14 3 10 8
3단계


4
0 1 2 3 4 5 6
2단계

5
11
1단계
S={0, 4, 1}
distance[]=
# define MAX_VERTICES 6 /*maximum number of vertices */
int cost[ ] {MAX_VERTICES} = /*cost matrix of Figure */
{{ 0, 50, 10, 1000,
45, 1000},
{1000,
0, 15, 1000,
10, 1000},
{ 20, 1000,
0,
15, 1000, 1000},
{1000, 20, 1000,
0,
35, 1000},
{1000, 1000, 30, 1000,
0, 1000},
{1000, 1000, 1000,
3, 1000,
0,}}
int distance [MAX_VERTICES];
short int found [MAX_VERTICES]; /* for set S */
int n = MAX_VERTICES;
/* distance [ i ] represents the shortest path from source vertex v to
i , found [ i ] holds a 0 if the shortest path to vertex i has not been
found and a 1 if it has, cost is the adjacency matrix */
/* iterate n -2 times : n -1 (source vertex) -1 (last vertex) */
for ( i = 0 ; i < n - 2 ; i++ ) {
u = choose (distance , n , found ) ;
found [ u ] = TRUE ;
for ( w = 0 ; w < n ; w++ )
if ( !found [ w ]) /* if not in S */
if (distance [ u ] + cost [ u ] [w] < distance [ w ] )
distance [ w ] = distance [ u ] + cost [ u ][ w ];
}
}
int choose (int distance [ ], int n , short int found [ ])
{
/* find vertex that has the smallest distance not yet checked.
void shortest path (int v, int cost[ ] [MAX_VERTICES],
int distance [ ], int n, short int found [ ] )
{
int i, u, w ;
for ( i = 0 ; i < n ; i ++ )
{
found [ i ] = FALSE ;
distance[ i ] = cost[v][i]
}
found [ v ] = TRUE ;
distance [ v ] = 0;
Found [ ] indicates elements in S */
int i , min , minpos ;
min = INT_MAX ;
minpos = -1 ;
for (i = 0 ; i < n ; i++ )
if (distance [ i ] < min && !found [ i ] )
{
min = distance [ i ] ;
minpos = i ;
}
return minpos ;
}
• Analysis of shortest path
inner for loop : n times, outer for loop : n -2 times  total : O ( n² )
 Bellman-Ford Algorithm
6
U
X
Z,X,V,U,Y
7
-4
7
2
V
-3
8
Z

5
-2
9
Y
start vertex z
- sp( x, y, k ): 정점 x에서 y까지의 최단거리 k를 저장

Bellman-Ford Algorithm
- 각 edge가 weight 값을 negative 일 때 시작정점에서 임의의 정점까지
shortestpath를 찾는 algorithm
- 어떤 정점이 시작 정점까지의 최소 거리가 되는 edge를 선택했을 때, 정점 사
이에 cycle이 존재하면 a shortest - path 존재하지 않음( weight가 negative)
• 에너지의 흡수 ( + ), 방출 (- )등의 예
- 어떤 정점까지의 최소 거리로 간주 되었어도 algorithm이 수행하는 도중에 변
경 (weight가 negative)
- 최근에 선택된 정점의 인접노드(index)가 존재하지 않고 모든
vertex를 고려했을 때 stop!
 Start vertex Z에서 다른 정점까지의 shortest - path
5
-2
u
6
8
z
-3
7
x
2
v
-4
9
7
y

Problem
G내의 모든 vertex 쌍에 대하여 shortest path를 계산

Solution

Dynamic programming algorithm
1.G내의 모든 vertex를 source로 하여 function shortest path를 이용하여 해결
가능: O(n³)
2.Dynamic programming method : O(n³)이지만 더 작은 constant factor를 가짐
- A [ i ][ j ]: index 가 k이하인 중간 vertex만을 사용할 경우의 i에서 j로 가는
shortest path의 cost
- G에 n -1보다 큰 index를 가진 경우는 존재하지 않으므로 i에서 j로 가는
n-1
shortest path의 cost는 A [ i ][ j ]이다.
- K= -1일 경우의 i에서 j로 가는 path는 중간 vertex를 하나도 허용하지 않으므로
-1
A [ i ][ j ]= cost [i ][ j ]이 다.
- 전체 algorithm은 A-1  A 0  ....  A n-1 을 구하는 과정이다.
k
Ak-1  AK 의 계산
1. path가 k를 지나지 않으면, Ak [ i ][ j ] = A k-1[ i ][ j ]
2.지나면, Ak [ i ][ j ] = Ak-1[ i ][ k ] + Ak-1[ k ][ j ]이다. 이 경우 path는 i에서 k를
거쳐 j로 간다.
이를 수식으로 표현하면
A k [ i ][ j ] = min {A k-1[ i ][ j ], Ak-1[ i ][ k ]+Ak-1[ k ][ j ]}, k  0
A - 1[ i ][ j ] = cost [ i ][ j ]
 Floyd-Warshall Algorithm
1
4
2

10
6
3
2
3
10
Ak [ i , j ] = min { Ak-1 [ i , j ] , Ak-1[ i , k ] + A k-1[ k , j ] }
K보다 큰 인덱스를 갖는 정점을 통과하지 않고
i에서 j로 가는 최단경로 비용
• Floyd - Warshall Algorithm
4
2
10
1
6
3
2
10
3

0 4 10
6 0 2
3 10 0
= cost [ i , j ]
A°[ i , j ]
- Ak [i, j] : k보다 큰 index를 갖는 정점을 중간에 통과하지 않고 i에서j로
가는 최단경로의 비용
- Graph G = (V, E, W)  “adjacency matrix” 로 표현
- wi,j =
0
i = j
weight of directed edge (i, j)
i  j & (i, j)  E

i  j & (i, j)  E
k
k-1
k-1
k-1
- A [ i , j ] = min { A [ i , j ], A [ i , k ] + A [ k , j ] } 이용
중간 노드 “1” 을 고려
1) A¹[ i , j ] , k = 1
A¹[ 1 , 1 ] = min { A°[ 1 , 1 ] , A°[ 1 , 1 ] + A°[ 1 , 1 ] } = 0
A¹[ 1 , 2 ] = min { A°[ 1 , 2 ] , A°[ 1 , 1 ] + A°[ 1 , 2 ] } = 4
A¹[ 1 , 3 ] = min { A°[ 1 , 3 ] , A°[ 1 , 1 ] + A°[ 1 , 3 ] } = 10
A¹[ 2 , 1 ] = min { A°[ 2 , 1 ] , A°[ 2 , 1 ] + A°[ 1 , 1 ] } = 6
.
.
.
.
.
.
.
.
.
.
.
.
A¹[ 3 , 1 ] = min { A°[ 3 , 1 ] , A°[ 3 , 1 ] + A°[ 1 , 1 ] } = 3
A¹[ 3 , 2 ] = min { A°[ 3 , 2 ] , A°[ 3 , 1 ] + A°[ 1 , 2 ] } = 7
A¹[ 3 , 3 ] = min { A°[ 3 , 3 ] , A°[ 3 , 1 ] + A°[ 1 , 3 ] } = 0
 A1[ i , j ] =
0 4 10
6 0 2
3 10 0
(
0 4 6
6 0 2
3 7 0
)
4
2
10
1
6
3
2
10
3
• A²[ i , j ], k = 2
0 4 10
6 0 2
3 10 0
중간 노드 “2” 를 고려!
A²[ 1 , 1 ] = min { A¹[ 1 , 1 ] , A¹[ 1 , 2 ] + A¹[ 2 , 1 ] } = 0
.
.
.
.
.
.
.
.
.
.
.
.
A²[ 1 , 3 ] = min { A¹[ 1 , 3 ] , A¹[ 1 , 2 ] + A¹[ 2 , 3 ] } = 6
.
.
.
.
.
.
.
.
.
.
.
.
 A²[ i , j ] =
A²[ 3 , 3 ] = min { A¹[ 3 , 3 ] , A¹[ 3 , 2 ] + A¹[ 2 , 3 ] } = 0
• A³[ i , j ], k = 3
(
4
A³[ 2 , 1 ] = min { A²[ 2 , 1 ] , A²[ 2 , 3 ] + A²[ 3 , 1 ] } = 5
.
.
.
.
.
.
.
.
.
.
.
.
A³[ 3 , 3 ] = min { A²[ 3 , 3 ] , A²[ 3 , 3 ] + A²[ 3 , 3 ] } = 0
2
 A³[ i , j ] =
)
10
1
6
중간 노드 “3” 를 고려!
A³[ 1 , 1 ] = min { A²[ 1 , 1 ] , A²[ 1 , 3] + A²[ 3 , 1 ] } = 0
.
.
.
.
.
.
.
.
.
.
.
.
0 4 6
6 0 2
3 7 0
3
2
10
0 4 6
5 0 2
3 7 0
3
( )


int distance [MAX_VERTICES][MAX_VERTICES]
void allcosts (int cost[ ] [MAX_VERTICES], int n)
{
/* determine the distance from each vertex to every vertex except itself, cost is
the adjacency matrix, distance is the matrix of distance */
int i, j, k;
for ( i = 0; i < n; i ++ )
for ( j = 0; j < n; j++)
distance [ i ][ j ] = cost [ i ][ j ];
for ( k = 0; k < n; k++ )
for ( i = 0; i < n; i++ )
for ( j = 0; j < n; j++ )
if (distance [ i ][ k ] + distance [ k ][ j ] < distance [ i ][ j ] )
distance [ i ][ j ] = distance [ i ][ k ] + distance [ k ][ j ];
}
Analysis of allcosts
세 개의 for loop : O (n³)

Definition of Transitive Closure
- directed graph G의 transitive closure matrix A+ 는 i 에서 j로 가는 length > 0인
path가 존재하면 A+[ i ][ j ]=1, 아니면 A+ [ i ][ j ]=0인 matrix이다.
- directed graph G의 reflexive transitive closure matrix A* 는 i에서 j로 가는
length  0인 path가 존재하면 A* [ i ][ j ]=1, 아니면 A* [ i ][ j ] = 0인 matrix이다.
• A+ 와 A* 는 대각선의 값만 다르다. A* 의 경우에는 모든 대각선의 값이 1이지만,
A+ 의 경우에는 vertex i 를 포함하는 length > 1인 cycle이 존재하면 A+[ i ][ j ]=1
이다.
• A+ 는 function allcosts를 이용하여 계산할 수 있으며 cost [ ][ ]는 다음과 같이
정한다.
cost [ i ][ j ] = 1 , if < i ,j >  E(G)
cost [ i ][ j ] = +  , if < i , j > E(G)
• allcosts 수행 완료 후 A+[ i ][ j ] = 1 iff distance [ i ][ j ] <+ 
• total 수행시간 : O( n³ )

Warshall Algorithm
1
2
4
3
0100
1010
0001
0000
1111
1111
0001
0000
Transitive Closure Matrix
 function allcosts를 약간 수정하여 A+를 직접 구할 수 있다.
for loop속의 if문을
distance[i][j]=distance[i][j] ||
distance[i][j] && distance[i][j];
로 변경하고 distance를 graph의 adjacency matrix 로 초기화 하면
(즉, distance[i][j]=1 , if<i, j> E(G) , distance[i][j]=0, if not)
distance의 최종 값이 A+가 된다.
 undirected graph의 경우 connected components를 계산하면 되므로
(reflexive) transitive closure matrix는 O(n²)으로 계산 가능
• Definition
-
Activity on vertex(AOV)network는 vertex는 task 또는 activity를, edge는 task사이의 선 후 관계를
나타내는 directed graph G이다.
- AOV network G에서 vertex i에서 vertex j로 가는 directed path가 있을 경우 vertex i를 vertex j의
predecessor라고 한다.
- AOV network G에서 <i, j>가 G의 edge일 경우 vertex i를 vertex j의 immediate predecessor라고 한
다.
예) 전산학 학위 취득(project)를 위해서는 수강이 필요한 과목(activity)들이 있으며, 과목간에는
선수 과목(prerequistics)의 관계가 있을 수 있다. Vertex는 과목, edge는 선수 과목 관계를 나타
내는 directed graph 즉, AOV network로 이 상황을 표현할 수 있다.
• Definition
- relation •이 모든 triples i, j, k 에 대하여, i • j and j •k -> i •k 이면 transitive하다고 한다.
- 집합 S의 모든 요소 i에 대하여 i •i가 true이면, relation은 S에 대하여 reflexive하다고 한다.
- 집합 S의 요소 i, j에 대하여 i •j, j •i는 i=j를 의미할 때 relation 은 S에 대하여 antisymmertric하다고
한다.
- partial order는 reflexive, antisymmertric, and transitive한 relation이다.
Course number Course name
Prerequisites
C1
PL I
None
C2
Discrete Mathematics
None
C3
Data Structures
C1,C2
C4
Cal 1
None
C5
Cal 2
C4
C6
Linear Algebra
C5
C7
Analysis of Algorithms
C3,C6
C8
Assembly Languages
C3
C9
Operating Systems
C7,C8
C10
Programming Languages C7
C11
Compiler Design
C10
C12
Aritificial Intelligence
C7
C13
Computational Theory
C7
C14
Parallel Algorithms
C13
C15
Numerical Analysis
C5
(a) Courses needed for a computer science degree at a
hypothetical university
C8
C1
C
9
C10
C3
C11
C7
C12
C2
C13
C4
C5
C6
C15
(b) AOV network representing courses as
vertices and edges as prerequisites
C14
• Definition
- 아래와 같은 성질을 가지는 graph의 vertex를 간의 linear ordering이다.
network에서 i가 j의 predecessor이면 topological order 상에서 i는 j보다 앞
에 존재한다.
- Algorithm for topological ordering
1. predecessor가 없는 임의의 vertex하나를 선택하여 출력한다.
2. network에서 이 vertex와 이 vertex에 연결된 모든 edge들을 제거한다. 모든
vertex 가 출력되던지 , 남은 vertex 들에 모두 predecessor들이 존재하여 아
무 vertex도 제거할 수 없을 때까지 step 1을 수행한다. (두번 째 경우는network
에 cycle이 존재하여 infeasible한 project인 경우이다. )
- formal description of topological sort
for(=0;<n;++) {
if every vertex has a predecessor {
fprintf(stderr, “Network has a cycle.\n”);
exit(1);
}
pick a vertex v that has no predecessors;
output v;
delete v and all edges leading out of v from the network;
}
V1
V0
V1
V1
V2
V4
V2
V4
V3
V5
V3
V5
(a) initial
V1
4
V5
(b) V0
V1
V
V2
(c) V3
V4
V4
V4
V5
(d) V2
(e) V5
(f)V1
Topological order generated: V0, V3, V2, V5 ,V1, V4
(g) V4
AOV network를 위한 데이터 구조
1. vertex의 predecessor존재 여부를 알아야 한다. 이를 위해서 각 vertex별로 immediate predecessor의
개수를 유지 하는 count field를 사용한다.
2. vertex와 이에 incident한 edge들을 제거할 수 있어야 한다. 이를 위해서 network를 adjacency list로
유지한다. vertex v 와 연결된 edge를 모두 제거하려면 vertex v의 adjacency list에 연결된 모든
vertex 들의 predecessor count 를 감소시킨다. Vertex의 count가 0이 되면 vertex를 zero count vertex
list에 위치시켜서 다음에 처리할 vertex를 선택할 때 사용한다.
변수 선언
typedef struct node *node_pointer;
typedef struct node
{
int vertex;
node_pointer link;
};
typedef struct
{
int count;
node_pointer link;
} hdnodes;
hdnodes graph[MAX_VERTICES];
/*in-degree of a vertex*/
/*headnode*/
• count field는 그 vertex의 in-degree를, link field는 adjacency list의 첫번째 node를 가리키는 포인터
를 가진다. node는 vertex와 link field를 가진다. <i,j>가 입력되면 vertex j 의 count를 증가시킨다.
count field가 0인 head node의 count field는 stack을 연결하는 링크 필드로 사용한다.
count
first
data link
[0]
0
11
21
3
[1]
1
4
[2]
1
41
5
0
[3]
1
51
4
0
[4]
3
0
[5]
2
0
0
0
Topological ordering 알고리즘에 의해 사용되는 내부 표현
void topsort (hdnodes graph[], int n)
{
int i, j, k, top;
node_pointer ptr;
/*create a stack of vertices with no predecessors*/
top=-1;
for( i=0 ; i < n ; i++ )
if (!graph[i].count) {
graph[i].count =top;
top=1;
}
for(i=0; i<n ; i++)
if(top=-1){
fprintf(stderr,”\nNetwork has a cycle.
\\ Sort terminated\n”);
exit(1);
}
else{
j=top;
/*unstack a vertex */
top=graph[top].count;
printf(“v%d,”,j);
for(ptr=graph[top].link; ptr; ptr=ptr->link){
/*decrease count of the successor vertices of j*/
k=ptr->vertex;
graph[k].count--;
if(!graph[k].count){
/*add a vertex k to the stack */
graph[k].count=top;
top=k;
} // if
} //for
} //else
} //function
Analysis of topsort
first for loop: O(n)
second for loop: O(n+e)
if:constant
else for loop:O(di)
total time:O(n+e)
• Activity on edge(AOE) network : edge는 task 또는 activity를, vertex는 activity의 완료를 알려 주는
event를 나타내는 directed graph G이다. event는 어떤 vertex에 들어오는 모든 activity가 완료 되었
을 경우 발생된다.
• Network evalution
1. Project수행에 필요한 최소 시간의 계산
2. Project 완료시간을 줄이기 위해 단축해야 할 activity를 색출
ex) PERT(performance evalution and review technique)
CPM(critical path method)
RAMPS(resource allocation and multiproject scheduling)
• Definition
- project 수행에 필요한 최소 시간은 activity들이 병렬로 수행될 수 있으므로 시작 vertex에서 끝 vertex
까지의 longest path이다. 이러한 longest path를 critical path라 하며, 한 network에 하나 이상 존재할 수 있
다.
- event vi가 일어날 수 있는 earliest time은 start vertex v0에서 vi까지의 longest path의 length이다.
event가 일어날수 있는 earliest time 은 그 vertex에서 나가는 모든 edge가 표현하는 activity의 earliest시
작 시간을 결정한다. activity ai의 earliest시작 시간을 early(i)로 나타낸다.
- activity ai의 latest time, late(i)는 project수행시간을 증가시키지 않고 activity를 시작할 수 있는 가장
늦은 시간으로 정의한다.
a0=6
start
V
V
a3=1
1
a1=4
a4=1
V
0
V
a6=9
a9=2
6
V
V
8
4
2
a7=7
a2=5
V
finish
a10=4
7
V
V
a8=4
3
5
a5=2
(a) AOE network. Activity graph of a hypothetical project
event
V0
V1
V4
V7
V8
interpretation
start of project
completion of activity a0
completion of activities a3 and a4
completion of activities a7 and a8
completion of project
(b) Interpretation of some of the events in the activity graph of (a)
• critical activity 는 early(i) = late(i) 인 activity를 의미한다.
early(i)와 late(i)의 차이는 그 activity가 얼마나 critical한가를 나타내는 measure이다.
즉, 그 activity를 얼마나 나중에 시작할 수 있는가를 나타낸다. 이 값은 critical path
analysis 에 유용하게 사용된다.
• early(i)와 late(i)의 계산
1. 먼저 모든 event j에 대하여, earliest event occurrence time, earliest[j]와 latest event
occurrence time, latest[j]를 구한다.
2. Activity ai가 edge<k,1>로 표현한다면 early(i)=earliest[k] late(i)=latest[1]- duration
of activity ai로 계산한다.
• earliest[j]와 latest[j]의 계산
forward stage 와 backward stage 의 두 단계를 거쳐 계산한다.
(start vertex 는 0으로 last vertex는 n-1으로 numbering되어 있다고 가정)
• earliest[j]의 계산
1. earliest[0]=0
2. earliest[j]=max iP(j) {earliest[i]+ duration of<i,j>}
where P(j):j의 immediate predecessor의 집합
(topological order로 계산을 수행하면 earliest[i]는 이미 계산된 상태이다.)
• function topsort 의 마지막 if문 다음에 다음 문을 추가함으로써 계산 가능:
if(earliest[k]< earliest[j] + ptr-> duration)
earliest[k] = earliest[j] + ptr-> duration;
• latest[j]의 계산
1. latest[n-1]=earliest[n-1]
2. latest[j]=min iS(j) {latest[i]-duration of<j,i>}
where S(j):j 의 immediate successor의 집합
inverse adjacency lists 에 function topsort을 수행하면 (head node의 count field에는 outdegree를 저장), reverse topological order를 구할 수 있고, 마지막 if문 다음에 다음 문을 추가함
으로써 step 2계산 가능:
if (latest[k]> latest[j] - ptr->duration)
latest[k] = latest[j] - ptr->duration;
forward step의 계산 후에 topological order를 안 후에 latest[j]는 step2 의 수식을 이용하
여 바로 계산 가능.
1
6
a1 = 6
a4 = 1
a 10 = 2
a7 = 9
start
0
4
a2 = 4
8 finish
a8 = 7
a5 = 1
a 11 = 4
2
7
a3 = 5
a9 = 4
3
5
a6 = 2
(a) 프로젝트의 작업 네트워크
activity
의 미
0
프로젝트의 시작
작업 a1의 종료
작업 a4와 a5의 종료
작업 a8와 a9의 종료
프로젝트의 종료
1
4
7
8
(b) activity 의미
1
a1 = 6
6
a4 = 1
a10 = 2
a7 = 9
start 0
4
8 finish
a2 = 4
a8 = 7
a5 = 1
a3 = 5
a11 = 4
2
7
a9 = 4
3
5
a6 = 2
i
1
a4=1
k
4
2
a5=1
ee
[0] [1] [2] [3] [4] [5] [6] [7] [8]
Initial
0 0 0
0 0 0
0 0 0
Output 0 0 6 4
5 0 0
0 0 0
Output 3 0 6 4
5 0 7
0 0 0
Output 5 0 6 4
5 0 7
0 11 0
Output 2 0 6 4
5 5 7
0 11 0
Output 1 0 6 4
5 7 7
0 11 0
Output 4 0 6 4
5 7 7 16 14 0
Output 7 0 6 4
5 7 7 16 14 18
Output 6 0 6 4
5 7 7 16 14 18
Output 8
Stack
[0]
[3, 2, 1]
[5, 2, 1]
[2, 1]
[1]
[4]
[7, 6]
[6]
[8]
earliest(k) = maxiP(k) { earliest(i) + <i,k> time}
1
a1 = 6
6
a4 = 1
a10 = 2
a7 = 9
start 0
4
8 finish
a2 = 4
a8 = 7
a5 = 1
a3 = 5
a11 = 4
2
7
a9 = 4
3
5
a6 = 2
i
l
a7=9
6
4
le[8]=ee[8]=18
le[6]=min{le[8]-2}=16
le[7]=min{le[8]-4}=14
le[4]=min{le[6]-9, le[7]-7}=7
le[1]=min{le[4]-1}=6
le[2]=min{le[4]-1}=6
le[5]=min{le[7]-4}=10
le[3]=min{le[5]-2}=8
le[0]=min{le[1]-6, le[2]-4, le[3]-5}=0
latest(l) = miniS(l) { latest(i) - <l,i> time}
시간 차이가 가장 큰 것을 취함
a8=7
7
a1 = 6
6
a4 = 1
a10 = 2
a7 = 9
start 0
4
a2 = 4
8 finish
a8 = 7
a5 = 1
a3 = 5
임계도
이른 시작 시간 가장 늦은 시간
1
a11 = 4
2
7
a9 = 4
3
a6 = 2
5
작업
a1
a2
a3
a4
a5
a6
a7
a8
a9
a10
a11
early(i)=e(i)
0
0
0
6
4
5
7
7
7
16
14
1ate(i)=l(i) 1(i) – e(i) 1(i)–e(i) = 0
0
0
Yes
2
2
No
3
3
No
6
0
Yes
6
2
No
8
3
No
7
0
Yes
7
0
Yes
10
3
No
16
0
Yes
14
0
Yes
early, late 임계도 값
earliest
[0] [1] [2] [3] [4] [5] [6] [7] [8]
0
6
4
5
7
7 16 14 18
latest
[0] [1] [2] [3] [4] [5] [6] [7] [8]
0
6
6
8
7
10
vertex 기준
16
14
18
k
임계성
ai
l
early(i) = earliest(k)
late(i)=latest(l) – ai time