种树 (贪心)

题目出处
很显然想要种树最少就要尽量多地种在交叉点的位置,而交叉点又最容易出现在这段路程的后端与其后离这段路程最近的路程的前端,所以可以先依照每段路程的后端大小将路程排序,然后从第一段路程种树前先扫描是否已种过,如果已种过树的段数比这段路要求的最少种树数还要多,就遍历下一个路段:如果没达到最小种树再从这段路后端开始种树(为下一段交叉做准备)
附代码:

#include <iostream>
#include <algorithm>
using namespace std;
struct l{
    int a,b,c;
}A[10005];
int C[100000];
bool cmp(l n,l m){
    return n.b<m.b;
}
int main(){
    int t; cin>>t;
    int d; cin>>d;
    for(int i=0;i<d;i++){
        cin>>A[i].a>>A[i].b>>A[i].c;
    }
    sort(A,A+d,cmp); int res=0;
    for(int i=0;i<d;i++){
            for(int j=A[i].b;j>=A[i].a;j--){
                if(A[i].c==0) break;
                if(C[j]==1){
                    A[i].c--;
                }
            }
        for(int j=A[i].b;j>=A[i].a;j--){
            if(A[i].c==0) break;
            else if(C[j]==0){
                C[j]=1; res++;
                A[i].c--;
            }
        }
    }
    cout<<res<<endl;
}

发布了24 篇原创文章 · 获赞 2 · 访问量 465

猜你喜欢

转载自blog.csdn.net/chineseherofeng/article/details/104686836
今日推荐