zoukankan      html  css  js  c++  java
  • HDU1863 畅通project 【最小生成树Prim】

    畅通project

    Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
    Total Submission(s): 16722    Accepted Submission(s): 6987


    Problem Description
    省政府“畅通project”的目标是使全省不论什么两个村庄间都能够实现公路交通(但不一定有直接的公路相连。仅仅要能间接通过公路可达就可以)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编敲代码,计算出全省畅通须要的最低成本。
     


     

    Input
    測试输入包括若干測试用例。每一个測试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 )。随后的 N
    行相应村庄间道路的成本,每行给出一对正整数,各自是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时。所有输入结束,相应的结果不要输出。
     


     

    Output
    对每一个測试用例。在1行里输出全省畅通须要的最低成本。若统计数据不足以保证畅通,则输出“?

    ”。

     


     

    Sample Input
    3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100
     


     

    Sample Output
    3 ?

    最小生成树模板题。由于假设有n个村庄的话,若是能畅通。定有n-1条边将其联通以构成最小生成树,否则不畅通。

    #include <stdio.h>
    #include <string.h>
    #define maxn 102
    
    int map[maxn][maxn];
    bool vis[maxn];
    
    void Prim(int n)
    {
    	int len = 0, i, j, tmp, u, v, count = 0;
    	vis[1] = true;
    	while(count < n - 1){
    		for(i = 1, tmp = -1; i <= n; ++i){
    			for(j = 1; vis[i] && j <= n; ++j) //cut
    				if(map[i][j] != -1 && !vis[j] && (tmp == -1 || map[i][j] < tmp)){
    					tmp = map[i][j]; u = j; v = i;
    				}			
    		}
    		if(tmp != -1){
    			map[v][u] = -1;
    			len += tmp; ++count;
    			vis[u] = 1;
    		}else break;
    	}
    	if(count == n - 1) printf("%d
    ", len);
    	else printf("?

    "); } int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); int n, m, a, b, c, i; while(scanf("%d%d", &n, &m), n){ memset(map, -1, sizeof(map)); memset(vis, 0, sizeof(vis)); for(i = 0; i < n; ++i){ scanf("%d%d%d", &a, &b, &c); if(map[a][b] == -1 || c < map[a][b]) map[a][b] = map[b][a] = c; } Prim(m); } return 0; }


     

  • 相关阅读:
    对比使用Charles和Fiddler两个工具及利用Charles抓取https数据(App)
    Charles-安装和配置
    python算法-队列
    python算法-快速排序
    【Codeforces】383.DIV2
    static关键字
    UNIX环境高级编程--5
    【LeetCode】467. Unique Substrings in Wraparound String
    typedef关键字
    strcpy 和 memcpy自实现
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5247757.html
Copyright © 2011-2022 走看看