Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Comparator;
- import java.util.Scanner;
- /**
- * Created by krngrvr09 on 30/1/15.
- */
- public class OptimumDP {
- public static void main(String[] args){
- /*
- Inputs are of the format:
- 3(number of inputs)
- (start_time, end_time, weight)
- 7 8 9
- 4 5 6
- 1 2 3
- */
- Scanner scanner = new Scanner(System.in);
- ArrayList<SingleInputDP> inputs = new ArrayList<SingleInputDP>();
- int number_of_inputs = scanner.nextInt();
- int[] ps = new int[number_of_inputs];
- int[] opt = new int[number_of_inputs];
- //ps[j] is the largest index i(which is smaller than j), such that job i is compatible with j.
- //Being compatible means, the 2 jobs do not overlap.
- Arrays.fill(ps, -1);//initializing ps with -1
- Arrays.fill(opt, -1);//initializing ps with -1
- System.out.println(number_of_inputs);
- for(int i=0;i<number_of_inputs;i++){
- int start = scanner.nextInt();
- int end = scanner.nextInt();
- int weight = scanner.nextInt();
- inputs.add(new SingleInputDP(start,end,weight));
- }
- //Sorting in ascending order with respect to the ending times
- inputs.sort(new Comparator<SingleInputDP>() {
- @Override
- public int compare(SingleInputDP o1, SingleInputDP o2) {
- if(o1.end>=o2.end){
- return 1;
- }
- else{
- return -1;
- }
- }
- });
- print_inputs(inputs);
- // Populating the ps array. Definition provided above.
- for(int i=0;i<inputs.size();i++){
- for(int j=0;j<i;j++){
- System.out.println(inputs.get(i).start+"><"+inputs.get(j).end);
- if(inputs.get(i).start>=inputs.get(j).end){
- ps[i] = j;
- }
- }
- }
- print_ps(ps);
- compute_opt(number_of_inputs-1,inputs,ps,opt);
- System.out.println("\nresult is: "+opt[number_of_inputs-1]);
- }
- public static void print_ps(int[] ps){
- for(int i=0;i<ps.length; i++) {
- System.out.print(ps[i]+" ");
- }
- }
- public static void print_inputs(ArrayList<SingleInputDP> inputs){
- for(int i=0;i<inputs.size();i++){
- SingleInputDP single_input = inputs.get(i);
- System.out.println(single_input.start+" "+single_input.end+" "+single_input.weight);
- }
- }
- public static int compute_opt(int j, ArrayList<SingleInputDP> inputs, int[] ps, int[] opt){
- opt[0] = 0;
- for(int i=1;i<inputs.size();i++){
- opt[i] = max(inputs.get(j).weight+opt[ps[i]],opt[i-1]);
- System.out.print(opt[i]+" ");
- }
- // if(j==-1){
- // return 0;
- // }
- // else{
- // return max(inputs.get(j).weight+compute_opt(ps[j], inputs, ps),compute_opt(j-1,inputs,ps));
- // }
- return 0;
- }
- public static int max(int i, int j){
- if(i>=j){
- return i;
- }
- else{
- return j;
- }
- }
- }
- class SingleInputDP{
- int start;
- int end;
- int weight;
- public SingleInputDP(int start, int end, int weight) {
- this.start = start;
- this.end = end;
- this.weight = weight;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement