1931:【05NOIP普及组】校门外的树
2808:校门外的树
1.6编程基础之一维数组 06:校门外的树
C++参考代码一:
#include <iostream>
using namespace std;
int road[10000+10];
int main()
{
int l, m, s, e, cnt = 0;
cin >> l >> m;
//所有的位置都栽了树
for (int i = 0; i <= l; i++)
road[i] = 1;
for (int i = 0; i < m; i++)
{
cin >> s >> e;
for (int j = s; j <= e; j++) //start end
road[j] = 0;
}
for (int i = 0; i <= l; i++)
if (road[i] == 1)
cnt++;
cout << cnt;
return 0;
}
C++参考代码二:
#include<iostream>
using namespace std;
int s[10001];
int main()
{
int L,M,i,j;
int a,b,sum=0,ex,new;
cin>>L>>M;//输入马路长度与区域数目
for (i=0; i<M; i++)
{
cin>>a>>b;//输入起始点与终止点
for(j=a; j<=b; j++) //令范围内的树移走
s[j]=1;
}
for(i=0; i<=L; i++) //统计马路长度内被移走的树的数目
if(s[i]==1)
sum++;
//总共有L+1模树
ex=L+1;
new=ex-sum;//移走后的树的数目
cout<<new;
return 0;
}
python3代码:
# https://www.acwing.com/problem/content/424/
if __name__ == "__main__":
arr = []
n, m = map(int, input().split())
for _ in range(m):
l, r = map(int, input().split())
arr.append([l, r])
arr.sort()
res = n + 1
start = arr[0][0]
end = arr[0][1]
for i in range(1, m):
if arr[i][0] <= end:
end = max(arr[i][1], end)
else:
res -= end - start + 1
start = arr[i][0]
end = arr[i][1]
res -= end - start + 1
print(res)