法一:暴力法,bool标记1和0之后进行统计
此处代码略······
法二:区间合并,引用PIIs直接区间首尾相减得到每个区间拔掉的树
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class 部落外的树 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//合并区间问题
List<PIIs> list = new ArrayList<PIIs>();
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
int n = scan.nextInt();
int m = scan.nextInt();
for(int i=0;i<m;i++) {
int l = scan.nextInt();
int r = scan.nextInt();
list.add(new PIIs(l,r));
}
Collections.sort(list);
//初始化边界为无穷
int start = Integer.MIN_VALUE;
int end = Integer.MIN_VALUE;
int []left = new int[m];
int []right= new int[m];
for(int i=0;i<list.size();i++) {
left[i]=((PIIs) list).getFirst();
right[i]=((PIIs) list).getSecond();
}
for(int i=1;i<m;i++) {
if(left[i]<right[i-1]) {
left[i]=left[i-1];
}
else {
int x=right[i-1]-left[i-1]+1;
n-=x;
}
}
int x=right[m-1]-left[m-1]+1;
n-=x; //减去最后一个区间
System.out.println(n);
}
}
class PIIs implements Comparable<PIIs>{
private int first, second;
public PIIs (int first, int second) {
this.first = first;
this.second = second;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
@Override
public int compareTo(PIIs object) {
return Integer.compare(first, object.first);
}
}