COOLING PIES - WA

#include <stdio.h>

int main()
{
 int t, piesOccupied;
 scanf("%d", &t);

while (t--)
{
    int n, i, j;
    scanf("%d", &n);
    
    piesOccupied = 0;
    
    int piesWeight[100];
    piesWeight[0] = 0;
    
    int racksWeight[100];
    racksWeight[0] = 0;
    
    for(i = 0; i < n; i++)
    {
        scanf("%d", &piesWeight[i]);
    }
    
    for(i = 0; i < n; i++)
    {
        scanf("%d", &racksWeight[i]);
    }
    
    for(i = 0; i < n; i++)
    {
        int min = 101;
        int loc = 101;
        for(j = 0; j < n; j++)
        {
            if(piesWeight[i] <= racksWeight[j])
            {
                if(min > racksWeight[j])
                {
                    min = racksWeight[j];
                    loc = j;
                }
            }
        }
        if(loc != 101)
        {
            racksWeight[loc] = 0;
            piesOccupied++;
        }
    }
    printf("%d\n", piesOccupied);
}

return 0;

}

This problem requires a greedy solution.

You are placing the pies in the order in which they are given, which is not a optimum way in the greedy approach.

First, you need to sort the array in ascending order, first, sort piesWeight[].

By this, you will be placing the pies in the increasing order by weight.

And then apply your approach, that is to find the smallest weight unoccupied rack.

Corrections:

  1. After taking input for array piesWeight[], sort it first.

  2. Also in the if condition ,if(loc!=101), place a else, as there is no need to check further.
    if(loc != 101)

    {

    racksWeight[loc] = 0;

    piesOccupied++;

    }

else

break;


If you still have any problem comment below.
1 Like

Thanks man :slight_smile: