30分求助!!

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

koduoriaseya @ 2023-01-17 11:12:55

#include<iostream>
#include<malloc.h>
using namespace std;
int main()
{

    bool* p;
    p=(bool*)malloc(10001 * sizeof(int));
    if (p == NULL) { cout << "default"; return 0; }
    memset(p, 1, 10001);
    int n, num_1;

    cin >> n >> num_1;
    while (num_1--)
    {
        int a, b;
        cin >> a >> b;
        for (int i = a; i <= b; i++)
        {
            p[i] = 0;
        }

    }
    int ans = 0;
    for (int i = 0; i <= n; i++)
    {
        if(p[i])
        ans++;
    }
    free(p);
    cout << ans;
return 0;
}

by Hongzixuan0922 @ 2023-01-17 11:20:48

malloc可能分配失败


by Hongzixuan0922 @ 2023-01-17 11:25:37

直接这样


#include<iostream>
#include<malloc.h>
#include <cstring>
using namespace std;
int main()
{
    bool p[10005];
    memset(p, 1, 10000);
    int n, num_1;
    cin >> n >> num_1;
    while (num_1--)
    {
        int a, b;
        cin >> a >> b;
        for (int i = a; i <= b; i++)
        {
            p[i] = 0;
        }

    }
    int ans = 0;
    for (int i = 0; i <= n; i++)
    {
        if(p[i])
        ans++;
    }
    cout << ans;
return 0;
}

就过了


by zhanghanzhou @ 2023-01-18 10:07:12

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

你也可以试试这个


|