我的代码为啥过不了呢,求回答!

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

code233520 @ 2024-06-29 16:51:25

用的是区间合并,如果看完回答十分感谢!

#include <bits/stdc++.h>
using namespace std;
// l表示马路的长度,n表示区域的段数,st,ed表开始结束
int l, n, st, ed;
typedef vector<pair<int, int>> arr;
arr segs;
int func(arr segs)
{
    arr temp;
    int ans;
    sort(segs.begin(), segs.end());
    int st = -1e9, ed = -1e9;
    for (auto seg : segs)
    {
        if (ed < seg.first)
        {
            if (ed != -1e9)
                temp.push_back({st, ed});
            st = seg.first;
            ed = seg.second;
        }
        else
            ed = max(ed, seg.second);
    }
    if (ed != -1e9)
        temp.push_back({st, ed});
    for (auto seg : temp)
    {
        ans += seg.second - seg.first + 1;
    }
    return ans;
}

int main()
{
    cin >> l >> n;
    for (int i = 1; i <= n; i++)
    {
        cin >> st >> ed;
        segs.push_back({st, ed});
    }
    int ans = l + 1 - func(segs);
    printf("%d", ans);
    return 0;
}

by zkszks @ 2024-06-29 17:01:22

啊会不会写错了呢


by Demfoqzil_Fly @ 2024-07-05 20:34:33

试试这个:

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

by yuxiang_wang @ 2024-07-06 15:23:40

#include<bits/stdc++.h>
using namespace std;
int main(){
    int l,m,cnt=0;
    cin>>l>>m;
    bool tree[100010]={};
    for(int i=0;i<m;i++){
        int a,b;
        cin>>a>>b;
        for(int j=a;j<=b;j++)tree[j]=1;
    }
    for(int i=0;i<=l;i++)if(!tree[i])cnt++;
    cout<<cnt;
    return 0;
}

|