zoukankan      html  css  js  c++  java
  • 51Nod

    N个点M条边的无向连通图,每条边有一个权值,求该图的最小生成树。

    Input

    第1行:2个数N,M中间用空格分隔,N为点的数量,M为边的数量。(2 <= N <= 1000, 1 <= M <= 50000)

    第2 - M + 1行:每行3个数S E W,分别表示M条边的2个顶点及权值。(1 <= S, E <= N,1 <= W <= 10000)

    Output

    输出最小生成树的所有边的权值之和。

    Sample Input

    9 14
    1 2 4
    2 3 8
    3 4 7
    4 5 9
    5 6 10
    6 7 2
    7 8 1
    8 9 7
    2 8 11
    3 9 2
    7 9 6
    3 6 4
    4 6 14
    1 8 8

    Sample Output

    37

    适合入门写的基础题。

    代码:

    #include <cstdio>
    #include <algorithm>
    #include <cstring>
    #include <queue>
    
    using namespace std;
    
    const int MAXN = 1005;
    
    int N,M;
    
    int pre[MAXN];//记录点的祖先 
    
    struct Edge{//边结构体 
    	int from;
    	int to;
    	int value;
    	Edge(){}
    	Edge(int a,int b,int c):from(a),to(b),value(c){}
    };
    
    struct cmp{
    	bool operator()(struct Edge a,struct Edge b){
    		return a.value > b.value;
    	}
    };
    
    priority_queue<struct Edge,vector<struct Edge>,cmp> Q;
    
    int Find(int a){
    	if(pre[a] == a)return a;
    	return pre[a] = Find(pre[a]);
    	while(!Q.empty())Q.pop();
    }
    
    bool Judge(int a,int b){
    	int A = Find(a);
    	int B = Find(b);
    	if(A != B){
    		pre[A] = B;
    		return true;
    	}
    	return false;
    }
    
    int Num,Sum;//表示已经找到的边数;表示最小生成树的值。 
    
    void init(){//初始化函数,有需要在每组输入之前进行处理的都可以加到这里。 
    	Sum = Num = 0;
    	for(int i=1 ; i<=N ; i++)pre[i] = i;//初始化祖先为自己。 
    }
    
    int main(){
    	
    	int a,b,c;
    	while(scanf("%d %d",&N,&M)!=EOF){
    		init();
    		for(int i=0 ; i<M ; i++){
    			scanf("%d %d %d",&a,&b,&c);
    			Q.push(Edge(a,b,c));
    		}
    		while(!Q.empty() && Num<N-1){
    			if(Judge(Q.top().from,Q.top().to)){
    				Sum += Q.top().value;
    				++Num;
    			}
    			Q.pop();
    		}
    		printf("%d
    ",Sum);
    	}
    	
    	return 0;
    }



  • 相关阅读:
    < java.util >-- Set接口
    Codeforces 627 A. XOR Equation (数学)
    Codeforces 161 B. Discounts (贪心)
    Codeforces 161 D. Distance in Tree (树dp)
    HDU 5534 Partial Tree (完全背包变形)
    HDU 5927 Auxiliary Set (dfs)
    Codeforces 27E. Number With The Given Amount Of Divisors (暴力)
    lght oj 1257
    Codeforces 219D. Choosing Capital for Treeland (树dp)
    Codeforces 479E. Riding in a Lift (dp + 前缀和优化)
  • 原文地址:https://www.cnblogs.com/vocaloid01/p/9514094.html
Copyright © 2011-2022 走看看