Professional Documents
Culture Documents
Chuong 6 - Ky Thuat Giam de Tri - Sinh Vien PDF
Chuong 6 - Ky Thuat Giam de Tri - Sinh Vien PDF
Gii thut
void DFS(G) {
for (u V) {
coloru = WHITE;
parentu = NIL;
}
for (u V)
if (coloru == WHITE)
DFS_VISIT(u);
}
void DFS_VISIT(u V) {
coloru = GRAY;
for (mi nh v k vi nh u)
if (colorv == WHITE) {
parentv = u;
DFS_VISIT(v);
}
coloru = BLACK;
}
2
a
3
Gii thut
void
BFS(G, root) {
for (u V) {
coloru = WHITE;
parentu = NIL;
}
colorroot = GRAY;
Q = ;
enQueue(Q, root);
while (Q ) {
u = deQueue(Q);
for (mi nh v k nh u)
if (colorv == WHITE) {
colorv = GRAY;
parentv = u;
enQueue(Q, v);
}
coloru = BLACK;
}
}
4
Sp xp Topology
a
e
b
b
f
d
c
e
d
C4
C1
C1
C2
C2
C3
C2
C3
C5
C4
C5
C1
C1
C3
C4
C2
C3
C5
C4
1. Lp thng vo tay li
2. Gn b truyn ng
3. Gn tay li
4. Lp bn p v a
5. Lp n xe
6. Lp yn xe
7. Lp hp iu chnh tc
8. Lp (to) khung xe
9. Lp v xe vo vnh xe
10. Gn bnh xe vo khung xe
11. Lp vnh xe vo bnh xe (c)
C5
C1
C4
C3
C3
C55
C2
C2
Gii thut:
Topologicalsort(Graph G) {
Vertex indegree[0 .. |V|] = 0;
for (mi u V)
for (mi nh v k vi u)
indegree[v] ++;
for (mi v V)
if (indegree[v] == 0)
enQueue(Q, v);
while (!isEmpty(Q)) {
Vertex u = deQueue(Q);
Output(u);
for (mi nh v k vi u)
if( -- indegree[v] == 0 )
enQueue(Q, v);
}
}
C4
C4
C5
C5
C3
C5
C5
6
Gii thut Steinhause-Johnson-Trotter
Dy c 3 phn t
1.
3.
2.
4.
Dy c 4 phn t
1.
9.
2.
10.
3.
11.
4.
12.
5.
13.
6.
14.
7.
15.
8.
16.
Chng trnh
void SJT(int a[], int pos[], int dir[]) {
int k, i;
while (true) {
k = N;
PrintIt(a);
while (a[pos[k] + dir[k]] > k) {
dir[k] = -dir[k];
if (--k == 0)
return;
}
i = pos[k];
a[i] = a[i + dir[k]];
a[i + dir[k]] = k;
pos[k] = i + dir[k];
pos[a[i]] = i;
}
}
void main() {
int i;
int a[N + 2], pos[N + 2], dir[N + 2];
for (i = 1; i <= N; i++) {
a[i] = pos[i] = i;
dir[i] = -1;
}
a[0] = a[N + 1] = N + 1;
SJT(a, pos, dir);
}
5.
6.
17.
18.
19.
20.
21.
22.
23.
24.
7
Th t t in hc (lexicographic order)
Gii thut (Hm tm dy hon v k tip dy c truyn vo)
NextPerm(a[1 .. n]) {
k = n 1;
while (a[k] > a[k+1]) {
k--;
if (k == 0)
return;
}
i = n;
while (a[k] > a[i])
i--;
swap(a[k], a[i]);
r = n;
s = k + 1;
while (r > s) {
swap(a[r], a[s]);
r--;
s++;
}
}
1
{a1}
2
{a1}
{a2}
{a1, a2}
3
{a1}
{a2}
{a1, a2}
{a3}
{a1, a3}
{a2, a3}
8
Chng trnh (khng qui)
#include <stdio.h>
const int N = 3;
void main () {
int a[N] = {0}, k;
do {
PrintIt(a);
k = N - 1;
while (k >= 0 && a[k] == 1)
k--;
if (k >= 0) {
a[k] = 1;
for (k++; k < N; k++)
a[k] = 0;
}
} while (k >= 0);
}
Gray code
9
Bi ton Josephus
P1
P8
P7
P1
P2
Start
P6
P7
P4
P3
P2
P7
P7
P3
2nd round
P3
P4
P5
}
int
3rd round
P5
1st round
Start
P5
1st round
P5
P1
2nd round
P1
P6
P3
P5
P7
P1
10
void main() {
int
a[N + 1], median, k;
k = (N % 2) ? (N + 1) / 2 : N / 2 + 1;
a[N] = ;
median = Selection(a, 0, N - 1, k);
}
Tm kim ni suy
Gi tr
ar
ax > k
ax = k k
ax < k
al
x1 x+1
l
Ch mc