2021顺丰科技研发笔试: 深度优先算法的应用


/**
* 克里斯是一个赏金猎人,他平时需要完成一些任务赚钱,最近他收到了一批任务,但是受到时间的限制,他只能等完成其中的

 * 一部分,具体来说就是有 n 个任务,每个任务用 start, end ,money 来表示任务的开始时间,结束时间,和完成任务获得
* 的金钱,
* 克里斯是一个贪心的人,他想知道自己在任务不冲突的情况下,最多可以获得多少金钱
*
* 输入描述:
* 第一行一个数,表示任务的个数
* 记下来 n 行,每行三个数字,表示任务的 :start, end ,money
*
* 输出描述:
* 输出一个值,表示克里斯最多可以获得的金钱数量
*
* */
import java.util.*;
public class Hunter {
private static Task[] tasks;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
tasks = new Task[n];
for(int i =0;i<n;i++){
String[] line = scan.nextLine().split(" ");
int start = Integer.parseInt(line[0]);
int end = Integer.parseInt(line[1]);
int money = Integer.parseInt(line[2]);
tasks[i] = new Task(start,end,money);
}
scan.close();

Arrays.sort(tasks, new Comparator<Task>() {
@Override
public int compare(Task t0, Task t1) { return t0.start - t1.start; }
});
ArrayList<Integer> res = new ArrayList<>();
for(Task cur : tasks ){
findWay(cur,res,0);
}
Collections.sort(res);

System.out.println("能获得的最大金钱数是 : "+res.get(res.size()-1));

}
public static void findWay(Task cur , ArrayList<Integer> res,int sum ){
sum += cur.money;
ArrayList<Task> next = getNext(cur);
if(next.size()==0 ){
res.add(sum);
return;
}
for(Task nextOne : next ){
findWay(nextOne,res,sum);
}
}

public static ArrayList<Task> getNext(Task cur ){
ArrayList<Task> next = new ArrayList<>();
for(Task task : tasks){
if(task.start >= cur.end) next.add(task);
}
return next;
}
}

class Task{
int start;
int end;
int money;
public Task( int start, int end , int money){
this.start = start;
this.end = end;
this.money = money;
}
}
原文地址:https://www.cnblogs.com/1832921tongjieducn/p/13541280.html