חזור לתיקייה: גליון 3

hw3q2

חיפוש בתיקיה
Ctrl K
לחץ כאן או הקש Ctrl K כדי לחפש בכל התיקיה

    hw3q2

    02340114

    מבוא למדמח מ

    רשימות הרצאה לקריאה בשבת

    hw3q2

    הופק מתוך תקיית התואר של שקד

    uni-folder.vercel.app

    hw3q2.c

    הערה (קובץ קוד)

    קובץ זה הוא קובץ קוד מסוג C.

    #include <stdio.h>
    #include <stdbool.h>
    #include <stdlib.h>
    
    #define MAX_SEGMENTS 100 /* m is guaranteed to be between 1 and 100 */
    #define MAX_HEIGHT 1000
    
    bool isHeigherWallFromLeft(const int wall[], const int length,
        const int currentBlock, const int currentHeight)
    {
        for (int i = 0; i < currentBlock; i++)
        {
            if (wall[i] >= currentHeight)
            {
                return true;
            }
        }
    
        return false;
    }
    
    bool isHeigherWallFromRight(const int wall[], const int length,
        const int currentBlock, const int currentHeight)
    {
        for (int i = currentBlock + 1; i < length; i++)
        {
            if (wall[i] >= currentHeight)
            {
                return true;
            }
        }
    
        return false;
    }
    
    int findNumberOfWaterBlocks(const int wall[], const int length)
    {
        int numberOfWaterBlocks = 0;
    
        for (int i = 1; i < length - 1; i++)
        {
            for (int j = wall[i] + 1; j < MAX_HEIGHT; j++)
            {
                if (isHeigherWallFromRight(wall, length, i, j) &&
                    isHeigherWallFromLeft(wall, length, i, j))
                {
                    numberOfWaterBlocks++;
                }
                else
                {
                    break;
                }
            }
        }
    
        return numberOfWaterBlocks;
    }
    
    int buildWall(int wall[], const int length)
    {
        int numberOfFilled = 0, i, height;
        while (scanf("%d %d", &i, &height) == 2)
        {
            if (height > 0 && i >= 0 && i < length && height <= MAX_HEIGHT)
            {
                wall[i] += height;
                numberOfFilled++;
            }
        }
    
        return numberOfFilled;
    }
    
    int calc_trapped_water()
    {
        int m, wall[MAX_SEGMENTS] = {0};
    
        scanf("%d", &m);
        if (buildWall(wall, m))
        {
            return findNumberOfWaterBlocks(wall, m);
        }
    
        return 0;
    }
    
    int main()
    {
        printf("%d\n", calc_trapped_water());
        return 0;
    }