Counting Garlic - Mr. Garlic Buying Books && Mr. Garlic Picking Apples - (Greedy)

An entry-level greedy problem, sort from big to small, and skip the accumulation operation when the serial number is a multiple of 3.

#include<stdio.h>
#include<algorithm>
using namespace std;

bool cmp(int a,int b)
{
    return a>b;
}

int a[100005];

intmain()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
    }
    sort(a+1,a+n+1,cmp);
    int sum=0;
    for(int i=1;i<=n;i++)
    {
        if(i%3==0) continue;
        else sum+=a[i];
    }
    printf("%d\n",sum);
}


It can also be regarded as an entry-level greedy problem. Each time you select the two smallest numbers in the queue and merge them.

//This question feels a lot like a Huffman tree to me. .

The priority queue is cleverly used here. Since the top element of the stack is the smallest at the beginning of the priority queue, we take the negative operation when the number is stored, and then restore it to a positive number when accumulating.

#include<stdio.h>
#include<algorithm>
#include<queue>
using namespace std;

priority_queue<int>q;
int x[10005],n,a,b;

intmain()
{

    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&x[i]);
        q.push(-x[i]); // becomes negative, making the originally large number smaller, and letting the small number take precedence
    }
    int sum=0;
    while(q.size()!=1)
    {
        a=q.top(); q.pop();
        b=q.top(); q.pop();
        sum-=(a+b); //Because the negative number is stored at the beginning, so use subtraction to become positive
        q.push(a+b);
    }
    printf("%d\n",sum);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324702876&siteId=291194637