06-图6. 公路村村通(30) java

题目来源:
http://www.patest.cn/contests/mooc-ds/06-%E5%9B%BE6


解:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;

class Edge implements Comparable<Edge>
{
	private int source ;
	private int target ;
	private int cost ;
	public Edge(int source,int target, int cost)
	{
		this.source = source;
		this.target = target;
		this.cost = cost;
	}
	public int getSource() {
		return source;
	}
	public void setSource(int source) {
		this.source = source;
	}
	public int getTarget() {
		return target;
	}
	public void setTarget(int target) {
		this.target = target;
	}
	public int getCost() {
		return cost;
	}
	public void setCost(int cost) {
		this.cost = cost;
	}
	@Override
	public int compareTo(Edge o) {
		// TODO Auto-generated method stub
		if(this.cost > o.cost)
			return 1;
		else if(this.cost == o.cost)
			return 0;
		else return -1;
	}
	@Override
	public String toString() {
		return "Edge [source=" + source + ", target=" + target + ", cost="
				+ cost + "]";
	}
	
	
	
}

public class Main {
	
	public static void main(String[] args)
	{
		Scanner scanner = new Scanner(System.in);
		int N = scanner.nextInt() ; //城镇数目
		int M = scanner.nextInt() ; //候选道路
		int totalCost=0 ;//总花费
		Edge[] edges = new Edge[M] ;//所有边的集合,使用数组速度更快
		HashSet<Integer> arrived = new HashSet<Integer>(); //已经到达的城镇集合	
		HashSet<Edge> useEdges = new HashSet<Edge>(); //最终选择的边
		int[] root = new int[N+1] ;//根元素
		for(int i=0;i<=N;++i)
			root[i]=i;
		//M次输入
		for(int i=0;i<M;i++)
		{
			int source = scanner.nextInt();
			int target = scanner.nextInt();
			int cost = scanner.nextInt();
		
			Edge edge = new Edge(source,target,cost);
			edges[i]=edge;
		}
		//对所有的边排序
		Arrays.sort(edges);
		
	
		for(int i=0; i<M;i++)
		{
			
			Edge edge =edges[i];
			int se = edge.getSource();
			int tt = edge.getTarget();
			if( getRoot(root,se)!=getRoot(root,tt) )//加入当前的这条边不会形成环
			{		
					arrived.add(se); 
					arrived.add(tt);
					totalCost = totalCost +edge.getCost();
					useEdges.add(edge);		
					int rootT = getRoot(root,tt);
					int rootS = getRoot(root,se);
					if(rootS >=rootT)
						root[rootT]= rootS;
					else 
						root[rootS]= rootT;
				
					
			}
			//System.out.println(useEdges);
			if(useEdges.size()==(N-1)) // 如果所有城市都连通了
			{
				System.out.println(totalCost);
				return ;
			}
		}
		System.out.println(-1);
		
		
		
	}
	/*
	 * 查找element的根
	 * */
	public static int getRoot(int[] root , int element)
	{
		while(root[element]!=element)
		{
			element = root[element];
		}
		return element;
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值