最小生成树--prim算法(poj 2485)

来源:互联网 发布:ko.js 事件 编辑:程序博客网 时间:2024/06/08 20:08

2016.12.28

prim算法是求解最小生成树的一种算法,基本思路是贪心。从已知集合出发(初始已知集合是1个点),每次查找所能到达的点的最短路径,将与这条路径连接的点加入已知集合,同时更新所能到达的点的最短路径。

【题目简述】
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 of input is an integer T, which tells how many test cases followed.
The first line of each case 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. There is an empty line after each test case.
Output
For each test case, 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.

Sample Input
1
3
0 990 692
990 0 179
692 179 0
Sample Output
692

【解题思路】
最小生成树模板题

【代码实现】

#include <stdio.h>#include <string.h>int n;int w[505][505], d[505], vis[505];void init(void);int prim(void);int main(void){    int z;    scanf("%d", &z);    while (z--)    {        init();        printf("%d\n", prim());    }    return 0;}int prim(void){    int i, j, k, minn, ans, m;    m = -(1 << 30);    ans = 0;    d[1] = 0;    for (i = 1; i <= n; ++i)    {        minn = 1 << 30;        for (j = 1; j <= n; ++j)            if (d[j] < minn && !vis[j])            {                minn = d[j];                k = j;            }        vis[k] = 1;        ans += d[k];        m = m > d[k] ? m : d[k];        for (j = 1; j <= n; ++j)            if (!vis[j] && w[k][j] < d[j])                d[j] = w[k][j];    }    return m;}void init(void){    int i, j;    scanf("%d", &n);    for (i = 1; i <= n; ++i)        for (j = 1; j <= n; ++j)            scanf("%d", &w[i][j]);    memset(d, 0x3f, sizeof(d));    memset(vis, 0, sizeof(vis));}

【心得体会】
掌握prim算法求解最小生成树

0 0
原创粉丝点击