C language array problem _ tree outside the school gate _ notation

Title description

There is a row of trees on the road with length L outside the gate of a school, and the distance between every two adjacent trees is 11 meters. We can regard the road as a number line, one end of the road is at the position of 00 on the number line, and the other end is at the position of LL; each integer point on the number line is 0,1,2,...,L0,1,2,..., L, both plant a tree.

Because there are some areas on the road to build the subway. These areas are represented by their starting and ending points on the number line. It is known that the coordinates of the start point and the end point of any region are integers, and there may be overlapping parts between regions. Now we 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 are left on the road after all these trees are removed.

Problem solving ideas

Just looking at the title, I feel that the questions in this array focus on the treatment of overlapping parts. Taking two construction areas as an example, there are three cases: 1: two do not overlap; 2: two overlap (one is contained in the other) ); 3: Partially overlapped. At first I thought it would be done by simply listing each situation and adding and subtracting the number of trees in the overlapping part, but this is very complicated.

The best practice for this question is to use the notation method , that is, first create an array, make all its elements '1', and modify the value in each construction area to '0', so that there is no need to worry about too many overlapping parts Minus the tree.

Code

#include <stdio.h>
#include <stdlib.h>

int main()
{
    
    
    int l,m,count=0,i,j;
    int a[101][2],lu[10001]={
    
    '\0'};		//a储存所有区域的始末位置; lu储存马路上的树的位置
    scanf("%d %d",&l,&m);
    for(i=0;i<l+1;i++)
        lu[i]=1;							//l为马路长度,每棵树距离1米,树的个数为l+1,这里将所有树的位置标记为‘1’
    for(i=0;i<m;i++)
    {
    
    
        scanf("%d %d",&a[i][0],&a[i][1]); 		//对m个区域的始末位置赋值
    }
    for(i=0;i<m;i++)
    {
    
    
        for(j=a[i][0];j<=a[i][1];j++)
        {
    
    
            lu[j]=0;							//将每个区域的所在路的区间的值覆盖为‘0’,表示此段路被用作建设
        }
    }
    for(i=0;i<l+1;i++)
        if(lu[i]==1)
            count++; 			//遍历lu,记录'1'的个数,即未被占用的树的数目
    printf("%d",count);

}

Guess you like

Origin blog.csdn.net/SingDanceRapBall/article/details/93503029