aiaiask.com©

开花即结果 提问即答案

"C语言实现超市货物架商品查找算法"
原始问题:

"C语言实现超市货物架商品查找算法"

解析:这是一个经典的贪心算法问题。首先,我们需要创建一个二维数组来表示货物架,然后初始化每个格子的商品。接下来,我们需要遍历每个顾客,对于每个顾客,我们需要找到他想要的商品所在的格子,如果找到了就将他拿下来并购买它,然后立刻离开超市。最后,我们需要返回最后一个顾客是否找到了自己想要的商品。

代码如下:

#include <stdio.h>
#include <string.h>

int main() {
    int n, m;
    char goods[26];
    scanf("%d %d", &n, &m);
    for (int i = 0; i < n; i++) {
        scanf(" %c", &goods[i]);
    }

    bool customers_found = true;
    while (m--) {
        char customer_goods[26];
        int found = 0;
        scanf(" %c", &customer_goods[0]);
        for (int i = 1; i < n; i++) {
            if (goods[i] == customer_goods[0]) {
                found = 1;
                break;
            } else if (goods[i] == '.') {
                customers_found = false;
                break;
            }
        }
        if (found) {
            for (int i = 0; i < n; i++) {
                if (goods[i] == customer_goods[0]) {
                    goods[i] = '.';
                    break;
                }
            }
        } else {
            customers_found = false;
        }
    }

    if (customers_found) {
        printf("Yes
");
    } else {
        printf("No
");
    }

    return 0;
}

这段代码首先读取货物架的大小和顾客的数量,然后读取货物架上的商品。接着,我们使用一个布尔变量customers_found来标记是否所有的顾客都离开了超市。在循环中,我们读取每个顾客想要的商品,然后遍历货物架找到这个商品。如果找到了,我们就将这个商品拿下来并标记customers_found为false。最后,我们输出结果。

"C语言实现超市货物架商品查找算法"
https://www.aiaiask.com/ask/46844.html
AI / 模型DeepSeek
时间 / DATESeptember 10, 2023, 8:44 PM
语言zh-CN
IP / 区域陕西 西安