###70分求助

P1047 [NOIP2005 普及组] 校门外的树

zhazhaqi77 @ 2022-10-07 11:19:19

#include<stdio.h>
int main()
{
    int l,m;
    scanf("%d %d",&l,&m);//l=500;m=3
    int a[l];//共501个元素
    int i;
    for (i=0;i<=l;i++){
        a[i]=1;//用1标记未移走的树
    }
    int u,v;
    for(i=1;i<=m;i++){
        scanf("%d %d",&u,&v);
        int k=u;
        for(;k<=v;k++){
            a[k]=0;//用0表示移除的树
        }
    }
    int t=0,count=0;
    for (;t<=l;t++){
        if(a[t]==1){
            count++;
        }
    }
    printf("%d",count);
    return 0;
}

by chenzhiyuan0923 @ 2022-10-07 11:20:48

#include <bits/stdc++.h>
using namespace std;
int a[10000],s=0,L,m,x,y;
int main(){
    cin>>L>>m;
    for(int i=0;i<=L;i++) a[i]=1;
    for(int i=1;i<=m;i++){
        cin>>x>>y;
        for(int j=x;j<=y;++j) a[j]=0;
    }
    int s=0;
    for(int i=0;i<=L;i++) if (a[i]==1)s=s+1;
    cout<<s;   
    return 0;
}

by chenzhiyuan0923 @ 2022-10-07 11:24:45

int a[l];

可能这个要大一点?


by chenzhiyuan0923 @ 2022-10-07 11:26:37

@zhazhaqi77


by xtyz_why @ 2022-10-07 11:31:49

数组a[l]0l-1a[l]越界了。 定义的时候改成a[l+1]就可以了(虽然并不推荐这样写,推荐定义一个对这个题而言足够大的数组) 代码改好了,在下面

#include<stdio.h>
int main()
{
    int l,m;
    scanf("%d %d",&l,&m);//l=500;m=3
    int a[l+1];//共501个元素
    int i;
    for (i=0;i<=l;i++){
        a[i]=1;//用1标记未移走的树
    }
    int u,v;
    for(i=1;i<=m;i++){
        scanf("%d %d",&u,&v);
        int k=u;
        for(;k<=v;k++){
            a[k]=0;//用0表示移除的树
        }
    }
    int t=0,count=0;
    for (;t<=l;t++){
        if(a[t]==1){
            count++;
        }
    }
    printf("%d",count);
    return 0;
}

by zhazhaqi77 @ 2022-10-07 13:41:44

@xtyz_why 谢谢!!!


by zhazhaqi77 @ 2022-10-07 13:42:06

@xchenzhiyuan 谢谢!!!


|