// Prim
算法
根据
MST
性质。若点集合
U ~
点集合
V
存在一点最短路径
s~t,
则最小生成树必包含
s~t
这条路。
//
利用反证法(或者剪贴法)可以证明
// Prim
算法
是将整个图看成了两个集合,一个
U
,一个不在
U
里面的。
//
有向图
#include
"stdafx.h"
#include
#include
const
static
int
_VERTEX_NUM
= 5;
const
static
int
_MAX_CURR_EDGE_VALUE
= 10000;
int
arrayPathScheme
[
_VERTEX_NUM
][
_VERTEX_NUM
] =
{
0, 10, -1, 30, 100,
-1, 0, 50, -1, -1,
-1, -1, 0, -1, 10,
-1, -1, 20, 0, 60,
-1, -1, -1, -1, 0,
};
enum
{
VECTEX_IN_SET_SELECT
= 0,
VECTEX_IN_SET_NO_SELECT
= 1, };
struct
SchemeNodeInfo
{
std
::
vector
<
int
>
vecNextIndex
;
//
后向结点集合
};
SchemeNodeInfo
NodeEdgeInfo
[
_VERTEX_NUM
];
void
Travase
(
int
nBeginNode
);
int
_tmain
(
int
argc
,
_TCHAR
*
argv
[])
{
int
nVectexInSet
[
_VERTEX_NUM
];
for
(
int
i
= 0;
i
<
_VERTEX_NUM
; ++
i
)
nVectexInSet
[
i
] =
VECTEX_IN_SET_NO_SELECT
;
//
集合从
Select
到
( NoSelect
各个点的最短路径
)
int
nShortestSelectToNo
[
_VERTEX_NUM
];
//
先选取顶点
V0.
int
nBeginNode
= 0;
nVectexInSet
[
nBeginNode
] =
VECTEX_IN_SET_SELECT
;
int
nPrevNodeIndex
[
_VERTEX_NUM
];
for
(
int
i
= 0;
i
<
_VERTEX_NUM
; ++
i
)
{
nShortestSelectToNo
[
i
] =
arrayPathScheme
[
nBeginNode
][
i
];
NodeEdgeInfo
[
i
].
vecNextIndex
.
clear
();
nPrevNodeIndex
[
i
] =
nBeginNode
;
}
int
nVectexIndex
= -1;
int
nMinEdge
;
for
(
int
i
= 0;
i
<
_VERTEX_NUM
- 1; ++
i
)
{
nMinEdge
=
_MAX_CURR_EDGE_VALUE
;
for
(
int
j
= 0;
j
<
_VERTEX_NUM
; ++
j
)
{
if
(
VECTEX_IN_SET_SELECT
==
nVectexInSet
[
j
] )
continue
;
if
(
nShortestSelectToNo
[
j
] == -1 ||
nShortestSelectToNo
[
j
] == 0 )
continue
;
if
(
nShortestSelectToNo
[
j
] <
nMinEdge
)
{
nMinEdge
=
nShortestSelectToNo
[
j
];
nVectexIndex
=
j
;
}
}
int
nPreNode
=
nPrevNodeIndex
[
nVectexIndex
];
NodeEdgeInfo
[
nPreNode
].
vecNextIndex
.
push_back
(
nVectexIndex
);
nVectexInSet
[
nVectexIndex
] =
VECTEX_IN_SET_SELECT
;
//
更新
nShortestSelectToNo
for
(
int
j
= 0;
j
<
_VERTEX_NUM
; ++
j
)
{
if
(
VECTEX_IN_SET_SELECT
==
nVectexInSet
[
j
] )
continue
;
if
(
arrayPathScheme
[
nVectexIndex
][
j
] == -1 ||
arrayPathScheme
[
nVectexIndex
][
j
] == 0 )
continue
;
if
(
nShortestSelectToNo
[
j
] == -1 ||
arrayPathScheme
[
nVectexIndex
][
j
] <
nShortestSelectToNo
[
j
] )
{
nShortestSelectToNo
[
j
] =
arrayPathScheme
[
nVectexIndex
][
j
];
nPrevNodeIndex
[
j
] =
nVectexIndex
;
}
}
}
Travase
(
nBeginNode
);
system
(
"pause"
);
return
0;
}
void
Travase
(
int
nBeginNode
)
{
std
::
vector
<
int
>::
iterator
iBegin
=
NodeEdgeInfo
[
nBeginNode
].
vecNextIndex
.
begin
();
std
::
vector
<
int
>::
iterator
iEnd
=
NodeEdgeInfo
[
nBeginNode
].
vecNextIndex
.
end
();
if
(
iBegin
==
iEnd
)
return
;
int
nDestNode
;
for
( ;
iBegin
!=
iEnd
; ++
iBegin
)
{
nDestNode
= (*
iBegin
);
std
::
cout
<<
"Source Node-"
<<
nBeginNode
<<
" Dest Node-"
<<
nDestNode
<<
" Edge Value--"
<<
arrayPathScheme
[
nBeginNode
][
nDestNode
]<<
std
::
endl
;
Travase
(
nDestNode
);
}
}