`
bulote
  • 浏览: 1308220 次
文章分类
社区版块
存档分类
最新评论

最小生成树算法[prime]

 
阅读更多

最小生成树算法prime的具体算法这里不再赘述,很多地方都有介绍,下面着重介绍采用最小堆实现的基本原理。


使用最小堆时需要几个数据结构:

1> Index表,用来查找每个节点在堆中的具体位置

2> Node{int pos , int val}; 堆中的节点

pos,用来记录该节点在index表中的位置

val , 表示该节点与已经拓展的节点的最小距离,该结点需要时时改变。

3> del表,记录该元素是否已经拓展


需要用的几个方法:

keepHeap(int pos):

用来保持堆的性质,当删除堆顶时,需要交换最后一个元素到堆顶,然后从上向下保持堆。

adjustHeap(int pos , int val):

将堆中pos处的节点val变为为val,在本例中,val是比堆中已经存在元素小,因此只需要向上拓展堆。


算法流程如下:

1》 初始化堆:

void initHeap()
{
Heap[0].pos = 0;
Heap[0].val = 0;
Index[0] = 0;
HeapSize = N;
for (int i = 1; i < N; ++i)
{
Heap[i].val = INITMAX;
Heap[i].pos = i;
Index[i] = i;
}
memset(del , 0 , sizeof(del));
}


2>当heapsize != 0时, //第一层循环

弹出堆顶元素node. ,设该节点为u , (由于此步将顶部元素给删除了,因此需要keepHeap, 且del[u] = true)

对与node相邻的所有结点v //第二层循环

如果v还没拓展,且节点v在Heap中的val值小于 d(u , v) , 则需要修改堆中节点v的值为d(u,v), 这时需要adjustHeap(vpos , d(u,v));

将heapsize --; 继续循环。

del[u] = true,说明u已经被拓展。


由2可知,该算法的时间繁杂度为O(E * Log(N)); , 这是因为在第二循环遍历到了每个边,且调用addjustHeap时时间复杂度为log(N)。


下面是一个针对一个问题的实现 :

问题如下:

Description
The island nation of Flatopia is perfectly flat. Unfortunately, Flatopia has no public highways. So the traffic is difficult in Flatopia. The Flatopian government is aware of this problem. They're planning to build some highways so that it will be possible to drive between any pair of towns without leaving the highway system.

Flatopian towns are numbered from 1 to N. Each highway connects exactly two towns. All highways follow straight lines. All highways can be used in both directions. Highways can freely cross each other, but a driver can only switch between highways at a town that is located at the end of both highways.

The Flatopian government wants to minimize the length of the longest highway to be built. However, they want to guarantee that every town is highway-reachable from every other town.
Input
The first line is an integer N (3 <= N <= 500), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within [1, 65536]) between village i and village j.
Output
You should output a line contains an integer, which is the length of the longest road to be built such that all the villages are connected, and this value is minimum.
This problem contains multiple test cases!
The first line of a multiple input is an integer T, then a blank line followed by T input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.
The output format consists of T output blocks. There is a blank line between output blocks.
Sample Input
Copy sample input to clipboard
1

3
0 990 692
990 0 179
692 179 0
Sample Output
692








分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics