合理分配(贪心算法)

蒜头君生活的国度,经过一场大战之后,建立了一个新的国度。国王打算让那些将军们,每人选择一个自己喜欢的区间段(这些将军们守卫的地方类似中国的古长城,是一条线段)去守卫他的国家。

为了使最多的将军能守卫自己想守卫的地方,怎么的安排是最合理的呢?

长城的区间段是[1,1000]。任意两个将军守卫的地方不能有重合的地方,否则会出现争执。两个点之间的交集不算交集。

例如 1 2 和2 3 是没有交集的。

但是1 3 和 2 4 是有交集,是会产生冲突的。

下面是每位将军期望守卫的区间段。

2 324
320 424
259 342
371 888
264 634
909 982
117 653
677 929
656 707
297 915
904 943
309 564
564 601
675 876
33 89
363 912
226 952
86 129
216 339
258 857
 
package 蓝桥杯2018年B组第三次模拟赛;

import java.util.Arrays;
import java.util.Scanner;

public class 合理分配 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scan=new Scanner(System.in);
        ChangCheng[] ccs=new ChangCheng[20];
        for(int i=0;i<20;i++){
            ccs[i]=new ChangCheng(scan.nextInt(),scan.nextInt());
        }
        Arrays.sort(ccs);
        int count=1;
        int nowEnd=ccs[0].end;
        for(int i=1;i<20;i++){
            if(ccs[i].begin>=nowEnd){
                count++;
                nowEnd=ccs[i].end;
            }
            System.out.println(ccs[i]);
        }
        System.out.println(count);
    }
    
}
class ChangCheng implements Comparable<ChangCheng>{
    int begin;
    int end;
    public int getBegin() {
        return begin;
    }
    public void setBegin(int begin) {
        this.begin = begin;
    }
    public int getEnd() {
        return end;
    }
    public void setEnd(int end) {
        this.end = end;
    }
    @Override
    public String toString() {
        return "ChangCheng [begin=" + begin + ", end=" + end + "]";
    }
    public ChangCheng(int begin, int end) {
        super();
        this.begin = begin;
        this.end = end;
    }
    public ChangCheng() {
        super();
        // TODO Auto-generated constructor stub
    }
    @Override
    public int compareTo(ChangCheng cc) {
        if(this.end>cc.end){
            return 1;
        }
        else if(this.end<cc.end){
            return -1;
        }
        return 0;
    }
    
}

 

 

请计算出最多可以满足多少个将军的愿望。

posted @ 2018-03-25 11:49  henu小白  阅读(1117)  评论(0编辑  收藏  举报