牛牛的冰激凌(贪心)

牛牛的冰激凌(贪心)

思路:贪心。

先将冰淇淋时间从小到大排序,便于计算答案。

考虑要时间最少,肯定一次尽可能运 m m 个,我们很容易能算出最少运输次数是 c n t = m n cnt=\lceil\dfrac{m}{n}\rceil

因此必定要选取 c n t cnt 个时间点,且这 c n t cnt 个时间点至少有 c n t 1 cnt-1 个在排序的下标中相隔 n n ,所以余下的 r e s t = m ( m o d n ) rest=m\pmod n 作为一次运送。

显然将前 r e s t rest 最小的作为第一组是最好的,因为这样时间最少。

class Solution {
public:
    /**
     * 两个数表示答案
     * @param n int整型 一次运输的冰激凌数量
     * @param m int整型 总冰激凌数
     * @param t int整型 一次运输的时间
     * @param c int整型一维数组 表示每个冰激凌制作好时间<1e4
     * @param cLen int c数组长度
     * @return int整型vector
     */
    vector<int> icecream(int n, int m, int t, int* c, int cLen) {
          sort(c,c+m);int ans=-t;
          int rest=m%n;if(!rest) rest=n;
         for(int i=rest-1;i<m;i+=n){
             ans+=t;ans=max(ans,c[i]),ans+=t;
         }
        return {ans,m/n+(m%n!=0)};
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_45750972/article/details/107715100