2022.11.02 PM 04:00 by CBJ
來源 : https://zerojudge.tw/ShowProblem?problemid=b139 出題者 : NOIP 2005普及組 標籤 : 種樹法 難易度 : 1
解題想法 : 開一個陣列記錄每個位置的狀態,有樹->1,沒樹->0,對於每次的start,end,將[start,end]的陣列值改成0,最後計算陣列總和
//C language
//solution link(含註解): https://github.com/CBJ0519/CBJsProgramDiary.com/blob/main/zj/b139.c
#include<stdio.h>
#include<string.h>
int main(){
int L,M,a[10005];
scanf("%d%d",&L,&M);
memset(a,-1,sizeof(a));
while(M--){
int start,end;
scanf("%d%d",&start,&end);
for(int i=start;i<=end;i++) a[i]=0;
}
int sum=0;
for(int i=0;i<=L;i++) sum+=(-a[i]);
printf("%d\n",sum);
return 0;
}

//C++ language
//solution link(含註解): https://github.com/CBJ0519/CBJsProgramDiary.com/blob/main/zj/b139.cpp
#include<iostream>
#include<algorithm>
#include<numeric>
using namespace std;
int main(){
int L,M,a[10005];
cin>>L>>M;
fill(a,a+10005,1);
while(M--){
int start,end;
cin>>start>>end;
for(int i=start;i<=end;i++) a[i]=0;
}
cout<<accumulate(a,a+L+1,0)<<"\n";
return 0;
}

## Python language
## solution link(含註解): https://github.com/CBJ0519/CBJsProgramDiary.com/blob/main/zj/b139.py
L,M=map(int,input().split())
a=[1]*(L+1)
for i in range(M):
start,end=map(int,input().split())
for j in range(start,end+1): a[j]=0
print(sum(a))

發佈留言