[Lintcode] 629. Minimum Spanning Tree

给出一些Connections,即Connections类,找到一些能够将所有城市都连接起来并且花费最小的边。

如果说可以将所有城市都连接起来,则返回这个连接方法;不然的话返回一个空列表。

给出 connections = ["Acity","Bcity",1],["Acity","Ccity",2],["Bcity","Ccity",3],

返回 ["Acity","Bcity",1],["Acity","Ccity",2]。

class Connection {
	public String city1, city2;
	public int cost;
	public Connection(String city1, String city2, int cost) {
		this.city1 = city1;
		this.city2 = city2;
		this.cost = cost;
	}
}

public class MinimumSpanningTree {
    /**
     * @param connections given a list of connections include two cities and cost
     * @return a list of connections from results
     */
	public List<Connection> lowestCost(List<Connection> connections) {
        Collections.sort(connections, comp);
        Map<String, Integer> hash = new HashMap<String, Integer>();
        int n = 0;
        for (Connection connection : connections) {
            if (!hash.containsKey(connection.city1)) {
                hash.put(connection.city1, ++n);
            }
            if (!hash.containsKey(connection.city2)) {
                hash.put(connection.city2, ++n);
            }
        }

        int[] father = new int[n + 1];

        List<Connection> results = new ArrayList<Connection>();
        for (Connection connection : connections) {
            int num1 = hash.get(connection.city1);
            int num2 = hash.get(connection.city2);

            int root1 = find(num1, father);
            int root2 = find(num2, father);
            if (root1 != root2) {
                father[root1] = root2;
                results.add(connection);
            }
        }

        if (results.size() != n - 1) {
            return new ArrayList<Connection>();
        }
        return results;
    }

    static Comparator<Connection> comp = new Comparator<Connection>() {
        public int compare(Connection a, Connection b) {
            if (a.cost != b.cost) {
                return a.cost - b.cost;
            }
            if (a.city1.equals(b.city1)) {
                return a.city2.compareTo(b.city2);
            }
            return a.city1.compareTo(b.city1);
        }
    };

    public int find(int num, int[] father) {
        if (father[num] == 0) {
            return num;
        }

        return father[num] = find(father[num], father);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值