题解 | 剩下的树
剩下的树
https://www.nowcoder.com/practice/f5787c69f5cf41499ba4706bc93700a2
//剩下的树
#include <iostream>
#include <vector>
#include <stdio.h>
using namespace std;
//思路:马路可以看成是一个动态数组,如果有树,在位置上如果有树,其值为0;无树->1;
//最后循环遍历整个动态数组,记录值为0的个数,即为剩下的数的个数
//循环遍历整个动态数组最好用迭代器(获取元素的位置,相当于高级指针)
int main() {
int L, M;
scanf("%d%d", &L, &M);
int i, j, left, right;
vector<int> tree(L + 1);//0~L,一共L+1棵树,初始值为0
int num = 0; //剩下的树的数量
for (i = 0; i < M; ++i) {
scanf("%d%d", &left, &right);
for (j = left; j <= right; ++j) {
tree[j] = 1;
}
}
vector<int>::iterator tree1;//迭代器
for (tree1 = tree.begin(); tree1 != tree.end(); ++tree1) {
if (*tree1 == 0) {
num++;
}
}
printf("%d\n", num);
}
王道机试指南 文章被收录于专栏
这个专栏是参考王道机试指南中相关的练习题哦

查看7道真题和解析