选择区间
数轴上有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();
}
}