zoukankan      html  css  js  c++  java
  • prim普里姆 poj 1287 示例 [ 实现用到并查集 ]

    prim算法 : 初始化-> 找最小值,更新 - 重复 找 n-1 次。
    #include <iostream>
    #include <string>
    #include <cstring>
    #include <cstdlib>
    #include <cstdio>
    #include <cmath>
    #include <vector>
    #include <stack>
    #include <deque>
    #include <queue>
    #include <bitset>
    #include <list>
    #include <map>
    #include <set>
    #include <iterator>
    #include <algorithm>
    #include <functional>
    #include <utility>
    #include <sstream>
    #include <climits>
    #include <cassert>
    #define BUG puts("here!!!");
    
    using namespace std;
    const int N = 105;
    const int INF = 0x7fffffff;
    int cost[N][N];
    int lowc[N];
    bool vis[N];
    int n, m;
    void prim(int p) {
    	memset(vis, false, sizeof(vis));
    	memset(lowc, 0, sizeof(lowc));
    	for(int i = 1; i <= p; i++) {
    		if(cost[1][i] != -1) {
    			lowc[i] = cost[1][i];
    		}
    		else lowc[i] = INF;
    	}
    	vis[1] = true;
    	int sum = 0;
    	for(int i = 1; i < p; i++) {
    		int mini = INF, c = 0;
    		for(int j = 1; j <= p; j++) {
    			if(!vis[j] && lowc[j] < mini) {
    				mini = lowc[j];
    				c = j;
    			}
    		}
    		sum += mini;
    		vis[c] = true;
    		for(int j = 1; j <= p; j++) {
    			if(!vis[j] && cost[c][j] != -1 && cost[c][j] < lowc[j]) {
    				lowc[j] = cost[c][j];
    			}
    		}
    	}
    	cout << sum << endl;
    }
    int main() {
    	while(cin >> n, n) {
    		cin >> m;
    		memset(cost, -1, sizeof(cost));
    		int a, b, c;
    		for(int i = 0; i < m; i++) {
    			cin >> a >> b >> c;
    			if((cost[a][b] != -1 && c < cost[a][b]) || cost[a][b] == -1) {
    				cost[a][b] = cost[b][a] = c;
    			}
    		}
    		prim(n);
    	}
    	return 0;
    }
    

  • 相关阅读:
    0.计算机相关
    面试笔试大概会出现的问题其二
    uboot传递启动参数给内核
    移植uboot之裁剪和修改参数
    uboot移植之支持板子nand启动
    uboot移植之建立新板、初始化时钟/SDRAM/UART
    uboot移植之重定位
    uboot移植之重定位之前的启动过程
    uboot移植之初步编译
    输入子系统分析
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787207.html
Copyright © 2011-2022 走看看