Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Hiển thị bảng đơn hàng nhà hàng (Display Table of Food Orders in a Restaurant) trong C++

Cho danh sách đơn hàng orders, mỗi đơn: [customer, table, food]. Tạo "bảng hiển thị": hàng = số bàn (tăng dần), cột = tên món (thứ tự từ điển), ô = số lượng món đó bàn đó gọi. Hàng đầu là header.

Ví dụ

Đầu vào: [["Amal","3","Paratha"],["Bimal","10","Biryni"],["Amal","3","Fried Chicken"],["Raktim","5","Water"],["Raktim","5","Paratha"],["Deepak","3","Paratha"]]
Đầu ra: Header + 3 hàng dữ liệu (bàn 3,5,10).

Thuật toán

  1. Dùng map> đếm: bàn → (món → số lượng). map tự sắp bàn theo số (string so sánh từ điển, nhưng "10" < "3" → cần chuyển int hoặc custom comparator).
  2. Thu thập tập hợp tên món set (tự sắp xếp).
  3. Xây header: "Table" + các món.
  4. Duyệt các bàn theo thứ tự số (dùng vector pair để sort theo int).
  5. Mỗi bàn: tạo hàng bắt đầu bằng số bàn, sau đó số lượng từng món (0 nếu không có).

Triển khai C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    vector> displayTable(vector>& orders) {
        map> cnt;
        set foods;
        for (auto& o : orders) {
            int table = stoi(o[1]);
            cnt[table][o[2]]++;
            foods.insert(o[2]);
        }
        vector> res;
        vector header = {"Table"};
        header.insert(header.end(), foods.begin(), foods.end());
        res.push_back(header);
        for (auto& [table, mp] : cnt) {
            vector row = {to_string(table)};
            for (const string& f : foods)
                row.push_back(to_string(mp[f]));
            res.push_back(row);
        }
        return res;
    }
};

Độ phức tạp

  • Thời gian: O(O log O + T log T + F log F) với O đơn hàng, T bàn, F món.
  • Không gian: O(T * F) lưu bảng đếm.

Kết quả kiểm thử

Đầu vào: ví dụ trên
Đầu ra: [[Table,Biryni,Fried Chicken,Paratha,Water],[3,0,1,2,0],[5,0,0,1,1],[10,1,0,0,0]]