ZZULIOJ 1154: The tree outside the school gate, Java

ZZULIOJ 1154: The tree outside the school gate, Java

Question description

There is a row of trees on the road of length L outside the gate of a certain school. The distance between every two adjacent trees is 1 meter. We can think of the road as a number axis. One end of the road is at the position of 0 on the number axis, and the other end is at the position of L. Each integer point on the number axis, that is, 0, 1, 2,..., L, has a tree planted. .
Because some areas on the road are to be used for subway construction. These regions are represented by their starting and ending points on the number line. It is known that the coordinates of the starting point and the ending point of any region are integers, and there may be overlaps between regions. Now you need to remove the trees in these areas, including the two trees at the end of the area. Your task is to calculate how many trees will remain on the road after all of them are removed.

enter

The first line of input is an integer N, indicating that there are N sets of test data.

The first line of each set of test data has two integers L (1 <= L <= 10000) and M (1 <= M <= 100). L represents the length of the road and M represents the number of areas. The sum of L and M separated by a space.

Each of the next M lines contains two different integers, separated by a space, representing the coordinates of the starting and ending points of a region.

output

The output consists of N lines, each line contains only one integer, indicating the number of remaining trees on the road.

Sample inputCopy
2

500 3
150 300
100 200
470 471

10 2
3 7
6 8
Sample outputCopy
298
5
import java.io.*;
import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) throws IOException {
    
    
        Scanner sc = new Scanner(System.in);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        int T = sc.nextInt();
        while (T-- > 0) {
    
    
            int l = sc.nextInt();
            int m = sc.nextInt();
            int[] a = new int[l + 1];
            for (int i = 0; i < m; i++) {
    
    
                int L = sc.nextInt();
                int R = sc.nextInt();
                for (int j = L; j <= R; j++) {
    
    
                    a[j] = 1;
                }
            }
            int sum = 0;
            for (int i = 0; i <= l; i++) {
    
    
                if (a[i] == 0) {
    
    
                    sum++;
                }
            }
            bw.write(sum + "\n");
        }
        bw.close();
    }
}

Guess you like

Origin blog.csdn.net/qq_52792570/article/details/132609527