SRM144_DIV2

第一次面試被傷害了。。
發奮努力的開始記錄下自己刷topcoder。

200

public class Time{
    public String whatTime(int seconds){
        return String.format("%s:%s:%s", (seconds /3600), (seconds / 60 % 60), seconds % 60 );
    }
}

簡單的一道題,String.format,小白的我學到了這個


500

譯碼的問題,可以直接導出解碼的遞推公式,注意的是就是前後各多加一個位保存0,最開始的0是爲了保證遞推公式,最後邊的0是爲了保證有解,在沒有解的情況下最後一位就會爲‘1’

public class BinaryCode{
    public String[] decode(String message){
        String[] ret = new String[] {"", ""};
        int[] a = new int[message.length() + 2];
        for (int i = 0; i < 2; i++){
            a[a.length - 1] = 0;
            a[1] = i;
            for (int j = 0; j < message.length(); j++){
                a[j + 2] = (message.charAt(j) - '0') - a[j] - a[j + 1];
                if (a[j + 2] < 0 || a[j + 2] > 1 || a[a.length - 1] != 0){
                    ret[i] = "NONE";
                    break;
                }
                ret[i] += a[j + 1];
            }
        }
        return ret;
    }
}

1100

一個圖的遍歷,每個邊有cost,因爲是個樹,問題可以簡化爲,所有的邊的cost的兩倍和 - 從root的最大花銷路徑。因爲最後的路徑只走了一次,其他都是走了還要返回來。

public class PowerOutage{
        int[] f;
        int[] t;
        int[] d;
        int dfs(int s){
            int res = 0;
            for (int i = 0; i < f.length; i++){
                if (f[i] == s){
                    res = Math.max(res, dfs(t[i]) + d[i]);
                }
            }
            return res;
        }
    public int estimateTimeOut(int[] fromJunction, int[] toJunction, int[] ductLength){
        f = fromJunction;
        t = toJunction;
        d = ductLength;
        int n = fromJunction.length;
        int total = 0;
        for (int i = 0; i < n; i++){
            total += 2*d[i];
        }
        return total - dfs(0);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章