Blue Bridge Cup--Algorithm to improve non-overlapping line segments (Java)

Resource limit
Time limit: 1.0s Memory limit: 256.0MB
Problem description
  Given the coordinates l, r and their value v of the left and right endpoints of n line segments on the number line, please select a number of line segments without a common point (the endpoints Coincidence is also considered to have a common point), so that their value sum is the largest, and the maximum value sum is output.
Input format
  The first line is a positive integer n.

Next n lines, each line of three integers l, r, v represents the left endpoint, right endpoint and value of a line segment, respectively. l<r,v>0.
Output Format
  Output an integer representing the maximum value and sum.
Sample input
4
1 3 4
3 5 7
5 7 3
2 6 8
Sample output
8
Data size and convention
  n<=2000
  l,r,v<=1000000
—————————————— ———————————————————————————————————————
Refer to the original text

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

public class Main {
    
    
	static int[] dp = new int[1000005];
	static Edge[] edges = new Edge[2005]; 
	
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		for (int i = 0; i < n; i++) {
    
    
			int l = sc.nextInt();
			int r = sc.nextInt();
			int v = sc.nextInt();
			edges[i] = new Edge(l, r, v);
		}
		Arrays.sort(edges, 0, n, new Comparator<Edge>() {
    
    
			@Override
			public int compare(Edge o1, Edge o2) {
    
    
				if (o1.r != o2.r) {
    
    
					return o1.r - o2.r;
				} else {
    
    
					return o1.l - o2.l;
				}
			}
		});
		dp[edges[0].r] = edges[0].v;
		for (int i = 1; i < n; i++) {
    
    
			for (int j = 0; j < i; j++) {
    
    
				if (edges[i].l <= edges[j].r){
    
    
	                dp[edges[i].r] = Math.max(dp[edges[i].r], Math.max(edges[i].v, dp[edges[j].r]));
	            } else {
    
    
	                dp[edges[i].r] = Math.max(dp[edges[i].r], edges[i].v + dp[edges[j].r]);
	            }
			}
		}
		System.out.println(dp[edges[n-1].r]);
	}
}
class Edge {
    
    
	int l;
	int r;
	int v;
	
	public Edge(int l, int r, int v) {
    
    
		super();
		this.l = l;
		this.r = r;
		this.v = v;
	}
}

insert image description here

Guess you like

Origin blog.csdn.net/QinLaoDeMaChu/article/details/108704153