Greedy template

Greedy simple question

Model a boat

The boat is a general model of a certain size, and can only take two people.
The idea is to sort the data, from small to large, and then start from the smallest, the smallest and the largest sum to see if less than equal to the maximum volume, maximum range, then move forward until you find a maximum and minimum value and satisfy the condition
that the maximum value of the following data can own one boat

Multiple sets of data, each set of data consists of n + 1 rows, the first row of input n, m, n is the number, m is the ship's maximum load, then n perpetrator of quality, each river can only take 2 people , seeking the required minimum ship

Template 1

我的思路,构建左边界,右边界,数据递增,进行查找,但十分麻烦
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int main(){
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF){
        int gr[100005];

        for(int i=0;i<n;i++){
            scanf("%d",&gr[i]);
        }
        sort(gr,gr+n);

        int sum=0;
        int left=0;
        int right=n-1;
        int lastright=n-1;
        while(left<right){
            while(gr[left]+gr[right]>m){
//当数据只剩下两个,且相加和大于4且第一个数据和两倍大于4时,会无故加一,所以要加上以下代码,表明筛选过头了
                if(right==left)break;
                right--;
            }

            sum++;

            sum+=lastright-right;//最小值-匹配到的最大值的后面的数据
            left++;
            right--;
            lastright=right;//及时更新上一个right

        }
        if(left==right){
            sum++;
        }

        //putchar('\n');
        printf("%d\n",sum);

    }
    return 0;
}

A better idea is:

Template 2

Many people take the model

When building a relatively simple model of ideas decreasing array index since for i will increase, can operate on the maximum value, but if the previous minimum value, the first maximum bit removed, and the minimum value can not be changed, but the value of i will increase

//多人乘坐模型
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=1e5+5;
bool cmp(int a,int b){
    return a>b;
}
int main(){
    int n;
    while(scanf("%d",&n)!=EOF){
        int g[maxn];
        for(int i=0;i<n;i++){
            scanf("%d",&g[i]);
        }

        sort(g,g+n,cmp);

        int times=0;
        for(int i=0;i<n;i++){
            int sum=g[i]+g[n-1];
            if(sum<=4){
                n--;//最后一个数,即最小值不需要了,已经和最大值一起取坐车了
                times++;
                while(sum+g[n-1]<=4){//出现一辆车做多个人的情况
                    n--;//倒数第二个也不要了
                    sum+=g[n-1];
                }

            }else{
                times++;//取最大值单独坐车
            }

           // printf("%d %d\n",i,n-1);


        }
         printf("%d\n",times);
    }


    return 0;

}

Guess you like

Origin www.cnblogs.com/Emcikem/p/11333815.html