[topcoder]KingdomReorganization

http://community.topcoder.com/stat?c=problem_statement&pm=11282&rd=14724

这道题是最小生成树,但怎么转化是关键。首先是把所有的路都destroy掉,得到基本的MassiveCost,然后在选MST的过程中,遇上这些边相当于还回去,它们的cost就是-destroy[i][j]。这样转化完毕。

用Kruskal来做,注意生成Edge的过程,第二层循环j要从i+1开始,主要是避免把i到i的路也放进去。

此题算是比较经典的K算法的题了。(没有用并查集)

import java.util.*;
public class KingdomReorganization
{
    public int getCost(String[] kingdom, String[] build, String[] destroy)
    {
        ArrayList<Edge> edges = new ArrayList<Edge>();
        int len = kingdom.length;
        int basicCost = 0;
        // create edges with cost
        for (int i = 0; i < len; i++)
        {
            for (int j = i+1; j < len; j++)
            {
                Edge edge = new Edge();
                edge.a = i; edge.b = j;
                if (kingdom[i].charAt(j) == '0')
                {
                    edge.cost = getValue(build, i, j);
                }
                else
                {
                    int tmp = getValue(destroy, i, j);
                    basicCost += tmp;
                    edge.cost = -tmp;
                }
                edges.add(edge);
            }
        }
        // Kruskal algo
        Collections.sort(edges);
        int[] color = new int[len];
        for (int i = 0; i < len; i++)
        {
            color[i] = i;
        }
        int cost = basicCost;
        for (int i = 0; i < edges.size(); i++)
        {
            Edge e = edges.get(i);
            if (color[e.a] == color[e.b]) continue;
            cost += e.cost;
            int oldColor = color[e.a];
            for (int k = 0; k < len; k++)
            {
                if (color[k] == oldColor)
                {
                    color[k] = color[e.b];
                }
            }
        }
        return cost;
    }
    
    private int getValue(String[] costs, int i, int j)
    {
        char c = costs[i].charAt(j);
        if (c >= 'A' && c <= 'Z')
        {
            return c - 'A';
        }
        else 
            return c - 'a' + 26;
    }
}

class Edge implements Comparable<Edge>
{
    public int a;
    public int b;
    public int cost;
    public int compareTo(Edge rhs)
    {
        return this.cost - rhs.cost;
    }
}

  

转载于:https://www.cnblogs.com/lautsie/p/3350059.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值