zoukankan      html  css  js  c++  java
  • P1478 陶陶摘苹果(升级版)(sort(),时间优化,priority_queue)

    题目描述

    又是一年秋季时,陶陶家的苹果树结了 n 个果子。陶陶又跑去摘苹果,这次他有一个 a 公分的椅子。当他手够不着时,他会站到椅子上再试试。

    这次与 NOIp2005 普及组第一题不同的是:陶陶之前搬凳子,力气只剩下 s 了。当然,每次摘苹果时都要用一定的力气。陶陶想知道在 s<0 之前最多能摘到多少个苹果。

    现在已知 n 个苹果到达地上的高度 xi,椅子的高度 a,陶陶手伸直的最大长度 b,陶陶所剩的力气 s,陶陶摘一个苹果需要的力气 yi,求陶陶最多能摘到多少个苹果。

    输入格式

    第 1 行:两个数 苹果数 n,力气 s。

    第 2 行:两个数 椅子的高度 a,陶陶手伸直的最大长度 b。

    第 3 行~第 3+n1 行:每行两个数 苹果高度 xi,摘这个苹果需要的力气 yi

    输出格式

    只有一个整数,表示陶陶最多能摘到的苹果数。

    输入输出样例

    输入  
    8 15
    20 130
    120 3
    150 2
    110 7
    180 1
    50 8
    200 0
    140 3
    120 2
    输出  
    4

    说明/提示

    对于 100% 的数据,n5000, a50, b200, s1000, xi280, yi100。

    思路:这道题,很容易想到贪心算法,但是,洛谷上有一个点死活超时,在各种优化的情况下,终于发现问题:for(int i=0;i<k,s>=ap[i];i++)  for(int i=0;i<k&&s>=ap[i];i++) ‘,’ 和 ‘&&’ 的不同,导致运行超时。?????不过,确实学到了很多。

    代码:

    //解法1 
    #include<cstdio>
    #include<algorithm>
    #include<iostream>
    using namespace std;
    int main(){
        int n,s,a,b;scanf("%d%d%d%d",&n,&s,&a,&b);
        int num=0;
        b+=a;
        int h,w,k=0;
        int ap[5001];
        for(int i=0;i<n;i++){
            scanf("%d %d",&h,&w);
            if(h<=b&&w<=s){
                ap[k++]=w;
            }
        }
        sort(ap,ap+k);
        for(int i=0;i<k&&s>=ap[i];i++){
            s-=ap[i];
            num++;
        } 
        printf("%d",num);
    }
    
    //解法2 
    #include<iostream>
    #include<queue>
    #include<cstdio>
    using namespace std;
    priority_queue<int,vector<int>,greater<int> >pq;
    int main(){
        int n,s,a,b,h,f,count=0;
        scanf("%d%d%d%d",&n,&s,&a,&b);
        b+=a;//这是陶陶最大的高度
        for (int i=0;i<n;i++){
            scanf("%d%d",&h,&f);
            if (h<=b&&f<=s){
                pq.push(f);
            }
        }
        while (s>0&&s>=pq.top()){
            s-=pq.top();
            count++;
            pq.pop();
        }
        printf("%d",count);//然后把计数器输出来
    }

    遇到问题:

    1. for(int i=0;i<k,s>=ap[i];i++)  for(int i=0;i<k&&s>=ap[i];i++) ‘,’ 和 ‘&&’ 不同,以后统一写成 ‘&&’
    2. 函数名功能描述
      sort 对给定区间所有元素进行排序
      stable_sort 对给定区间所有元素进行稳定排序
      partial_sort 对给定区间所有元素部分排序
      is_sorted 判断一个区间是否已经排好序

      #include<algorithm>
      #include<iostream>
      using namespace std;

      这些都需要。
    3. //升序队列
      priority_queue <int,vector<int>,greater<int> > q;
      //降序队列
      priority_queue <int,vector<int>,less<int> >q;

     

  • 相关阅读:
    ListView点击事件
    ListView优化:
    自定义ListView
    ListView简单使用
    mysql中show processlist过滤和杀死线程
    自定义控件
    yum配置中driver-class-name: com.mysql.jdbc.Driver报错
    CSS+HTML
    maven的配置
    Model、ModelMap、ModelAndView的作用及区别
  • 原文地址:https://www.cnblogs.com/bjxqmy/p/12203831.html
Copyright © 2011-2022 走看看