题解 | #剩下的树#
剩下的树
https://www.nowcoder.com/practice/f5787c69f5cf41499ba4706bc93700a2
暴力解,
- 创建数组tree,长度为l+1,初始化tree数组每一位都是1,表示该树存在;
- 遍历数组tree,将输入区间内的树”删去“,即将对应的值置0,表示该树被删去;
- 遍历数组tree,对数值为1的树计数;
- 输出计数count。
时间复杂度O(n2),空间复杂度O(l)
#include <cstring>
#include <iostream>
using namespace std;
int main() {
int l, m;
while (cin >> l >> m) { // 注意 while 处理多个 case
int tree[l+1];
int from, to, count = 0;
for (int i = 0; i <= l; i++){
tree[i] = 1;
//cout<<tree[i]<<endl;
}
for (int i = 0;i < m; i++){
cin >> from >> to;
for (int j = from; j <= to; j++){
tree[j] = 0;
}
}
for (int i = 0; i <= l; i++){
if (tree[i] == 1) count++;
//cout<<tree[i]<<endl;
}
cout << count << endl;
}
}
// 64 位输出请用 printf("%lld")