【java】選擇區間 區間選點
阿新 • • 發佈:2019-01-05
選擇區間
數軸上有n個開區間(ai,bi),選擇儘量多個區間,使得這些區間兩兩沒有公共點。
樣例輸入;
5
1,4
5,6
3,4
6,7
4,5
樣例輸出:
1,4
4,5
5,6
6,7
import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; class Node implements Comparable<Node>{ int x; int y; public Node(int x,int y){ this.x=x; this.y=y; } public int compareTo(Node node) { if(this.y>node.y) return 1; else if(this.y<node.y) return -1; else return 0; } } public class Main { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); while(scanner.hasNext()) { int n=scanner.nextInt(); ArrayList<Node> list=new ArrayList<Node>(); scanner.nextLine(); for(int i=0;i<n;i++){ String s=scanner.nextLine(); String[] arr=s.split(","); Node node=new Node(Integer.parseInt(arr[0]),Integer.parseInt(arr[1])); list.add(node); } Collections.sort(list); ArrayList<Node> result=new ArrayList<Node>(); Node node=list.get(0); int y=node.y; result.add(node); for(int i=1;i<n;i++){ Node temp=list.get(i); if(temp.x>=y){ result.add(temp); y=temp.y; } } for(Node res:result){ System.out.println(res.x+","+res.y); } } scanner.close(); } }
區間選點
數軸上有n個閉區間[ai,bi],取儘量少的點,使得每個區間內都至少有一個點。
樣例輸入:
5
1,4
5,6
3,4
6,7
4,5
樣例輸出:
4 6
import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; class Node implements Comparable<Node>{ int x; int y; public Node(int x,int y){ this.x=x; this.y=y; } public int compareTo(Node node) { if(this.y>node.y) return 1; else if(this.y<node.y) return -1; else if(this.x>node.x) return -1; else if(this.x<node.x) return 1; else return 0; } } public class Main { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); while(scanner.hasNext()) { int n=scanner.nextInt(); ArrayList<Node> list=new ArrayList<Node>(); scanner.nextLine(); for(int i=0;i<n;i++){ String s=scanner.nextLine(); String[] arr=s.split(","); Node node=new Node(Integer.parseInt(arr[0]),Integer.parseInt(arr[1])); list.add(node); } Collections.sort(list); ArrayList<Integer> result=new ArrayList<Integer>(); Node node=list.get(0); int y=node.y; result.add(y); for(int i=1;i<n;i++){ Node temp=list.get(i); if(temp.x>y){ y=temp.y; result.add(y); } } StringBuffer str=new StringBuffer(); for(int i:result){ str.append(i+" "); } System.out.println(str.substring(0,str.length()-1)); } scanner.close(); } }