最大連續郵資問題的JAVA實現

 public class StampCost {
    int m;
    int n;
    int stamps[];
    int maxNum = 0;
    int[] tempset;
    int current;
    int rightPos;
    int base;
    public StampCost(int m,int n,int[] stamps){
        this.m = m;
        this.n = n;
        this.stamps = stamps;
        check();
        printResult();
    }
    
    public void check(){
        tempset = new int[stamps[(stamps.length-1)]*4+1];
        maxNum = m;//因爲第一個確定是1,所以初始化最大的面值就是 1*m
        for (int i=1;i<5;i++){
            int min = Math.max(stamps[i],maxNum)+1;;
            int max = stamps[i]*m;
            if (min < stamps[i]+1){
                return;
            }
            maxNum = min-1;
            tempset[maxNum]=1;
            if (!checkSpan(min,max,i)){
                return;
            }
        }
    }
    
    public boolean checkSpan(int min,int max,int rightPos){
        base = min;
        current=stamps[rightPos];
        this.rightPos = rightPos;
        backtrace(0);
        if (tempset[min] == 0){
            return false;
        }
        for (int i=min;i<max;i++){
            if (tempset[i] == 0){
                return true;
            }
            else{
                maxNum++;
            }
        }
        return true;
    }
    
    public void backtrace(int i){
        if (i >= (m-1)){
            return;
        }
        else{
            for (int j=0;j<rightPos+1;j++){
                current += stamps[j];
                if (current >= base){
                    tempset[current] = 1;
                }
                backtrace(i+1);
                current -= stamps[j];
            }  
        }
    }
    
    public void printResult(){
        System.out.println(maxNum);
    }
    
    
    
    
    public static void main(String args[]){
        int m=4;
        int n=5;
        int[] stamps={1,3,11,15,32};
        new StampCost(m,n,stamps);
    }
}
發佈了28 篇原創文章 · 獲贊 4 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章