粉刷房子 II

链接

假如有一排房子,共 n 个,每个房子可以被粉刷成 k 种颜色中的一种,你需要粉刷所有的房子并且使其相邻的两个房子颜色不能相同。

当然,因为市场上不同颜色油漆的价格不同,所以房子粉刷成不同颜色的花费成本也是不同的。每个房子粉刷成不同颜色的花费是以一个 n x k 的矩阵来表示的。

例如,costs[0][0] 表示第 0 号房子粉刷成 0 号颜色的成本花费;costs[1][2] 表示第 1 号房子粉刷成 2 号颜色的成本花费,以此类推。请你计算出粉刷完所有房子最少的花费成本。

注意:

所有花费均为正整数。

import java.util.Comparator;
import java.util.PriorityQueue;

class Solution {
    private void offerQueue(PriorityQueue<Info> minQueue, int index, int cost) {
        if (minQueue.size() < 2) {
            minQueue.offer(new Info(index, cost));
        } else {
            if (minQueue.peek().cost > cost) {
                minQueue.poll();
                minQueue.offer(new Info(index, cost));
            }
        }
    }

    public int minCostII(int[][] costs) {
        if (costs == null || costs.length == 0 || costs[0].length == 0) {
            return 0;
        }

        InfoComparator infoComparator = new InfoComparator();
        PriorityQueue<Info> minQueue = new PriorityQueue<>(infoComparator);

        int n = costs.length;
        int k = costs[0].length;
        for (int i = 0; i < k; ++i) {
            offerQueue(minQueue, i, costs[0][i]);
        }

        for (int i = 1; i < n; ++i) {
            Info two = minQueue.poll();
            Info one = minQueue.poll();
            for (int j = 0; j < k; ++j) {
                if (j != one.colorIndex) {
                    offerQueue(minQueue, j, costs[i][j] + one.cost);
                } else {
                    offerQueue(minQueue, j, costs[i][j] + two.cost);
                }
            }
        }
        minQueue.poll();
        return minQueue.peek().cost;
    }
}

class Info {
    int colorIndex;
    int cost;

    public Info(int colorIndex, int cost) {
        this.colorIndex = colorIndex;
        this.cost = cost;
    }
}

class InfoComparator implements Comparator<Info> {

    @Override
    public int compare(Info o1, Info o2) {
        return Integer.compare(o2.cost, o1.cost);
    }
}
posted @ 2021-10-14 13:38  Tianyiya  阅读(39)  评论(0)    收藏  举报