#include <iostream>
#include <vector>
#include <iomanip>
#include <limits>

using std::cin;
using std::cout;
using std::endl;
using std::setw;
using std::vector;


// 工具函数：读取一个整数，带基本的非法输入处理
int readInt() {
    int x;
    while (!(cin >> x)) {
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        cout << "输入无效，请输入整数：";
    }
    return x;
}

// 打印一条分隔线，便于阅读输出
void printLine(char ch = '-') {
    for (int i = 0; i < 70; ++i) cout << ch;
    cout << '\n';
}

// 打印当前系统状态：Available、Max、Allocation、Need
void printVector(const vector<int>& v, const char* title, const vector<char>& rname) {
    cout << title << "\n";
    cout << "    ";
    for (size_t j = 0; j < v.size(); ++j) {
        cout << "  " << rname[j];
    }
    cout << "\n    ";
    for (size_t j = 0; j < v.size(); ++j) {
        cout << setw(3) << v[j];
    }
    cout << "\n";
}

void printMatrix(const vector<vector<int>>& m, const char* title, const vector<char>& rname) {
    cout << title << "\n";
    cout << "    ";
    for (size_t j = 0; j < rname.size(); ++j) {
        cout << "  " << rname[j];
    }
    cout << "\n";
    for (size_t i = 0; i < m.size(); ++i) {
        cout << "P" << i << ": ";
        for (size_t j = 0; j < m[i].size(); ++j) {
            cout << setw(3) << m[i][j];
        }
        cout << "\n";
    }
}

void printState(const vector<int>& available,
                const vector<vector<int>>& maxNeeds,
                const vector<vector<int>>& alloc,
                const vector<vector<int>>& need,
                const vector<char>& rname) {
    printVector(available, "当前可用资源 Available:", rname);
    printMatrix(maxNeeds,   "各进程最大需求 Max:", rname);
    printMatrix(alloc,      "各进程已分配 Allocation:", rname);
    printMatrix(need,       "各进程仍需 Need:", rname);
}

// 安全性算法：
// 输入：Available、Allocation、Need
// 输出：是否安全以及一个安全序列（若安全）
bool safetyCheck(const vector<int>& available,
                 const vector<vector<int>>& alloc,
                 const vector<vector<int>>& need,
                 vector<int>& safeSeq) {
    int n = (int)alloc.size();          // 进程数
    int m = (int)available.size();      // 资源种类数

    vector<int> work = available;       // 临时工作向量 Work
    vector<int> finish(n, 0);           // Finish 标记，0=false, 1=true
    safeSeq.clear();
    safeSeq.reserve(n);

    // 重复寻找可以满足 Need[i] <= Work 的进程 i，将其“完成”，释放资源
    bool progress = true;
    while (progress) {
        progress = false;
        for (int i = 0; i < n; ++i) {
            if (finish[i]) continue;    // 已经完成的跳过

            bool canRun = true;
            for (int j = 0; j < m; ++j) {
                if (need[i][j] > work[j]) { // Need[i] <= Work ?
                    canRun = false;
                    break;
                }
            }

            if (canRun) {
                // 进程 i 可以顺利完成，释放其占有资源到 Work
                for (int j = 0; j < m; ++j) {
                    work[j] += alloc[i][j];
                }
                finish[i] = 1;
                safeSeq.push_back(i);
                progress = true; // 本轮有进展，下轮继续尝试
            }
        }
    }

    // 检查是否所有进程都能完成
    for (int i = 0; i < n; ++i) {
        if (!finish[i]) return false; // 存在不能完成的进程，状态不安全
    }
    return true; // 安全
}

// 银行家算法一次请求：
// 尝试将 request 分配给进程 pid，若保持系统安全则正式分配，否则回滚。
// 返回：true=分配成功；false=分配失败（含请求非法与不安全两种情况）。
bool bankerRequest(int pid,
                   const vector<int>& request,
                   vector<int>& available,
                   vector<vector<int>>& alloc,
                   vector<vector<int>>& need,
                   const vector<vector<int>>& maxNeeds,
                   vector<int>& outSafeSeq,
                   vector<char> rname) {
    int n = (int)alloc.size();
    int m = (int)available.size();

    // 1) 基本参数合法性判断
    if (pid < 0 || pid >= n) {
        cout << "错误：进程号超出范围。" << endl;
        return false;
    }
    if ((int)request.size() != m) {
        cout << "错误：请求向量维度不匹配。" << endl;
        return false;
    }

    // 2) Request <= Need ?
    for (int j = 0; j < m; ++j) {
        if (request[j] < 0) {
            cout << "错误：请求值不能为负数。" << endl;
            return false;
        }
        if (request[j] > need[pid][j]) {
            cout << "错误：请求量超过该进程最大剩余需求 Need。" << endl;
            return false;
        }
    }

    // 3) Request <= Available ?
    for (int j = 0; j < m; ++j) {
        if (request[j] > available[j]) {
            cout << "资源不足：系统当前 Available 不满足请求，请求进程需等待。" << endl;
            return false;
        }
    }

    // 输出试分配前的状态
    printLine('=');
    cout << "请求前系统状态如下：" << endl;
    printState(available, maxNeeds, alloc, need, rname);
    cout << "本次请求：P" << pid << " 请求向量 Request = (";
    for (int j = 0; j < m; ++j) {
        cout << request[j] << (j + 1 == m ? "" : ", ");
    }
    cout << ")" << endl;

    // 4) 试分配（假定分配）
    for (int j = 0; j < m; ++j) {
        available[j] -= request[j];
        alloc[pid][j] += request[j];
        need[pid][j] -= request[j];
    }

    // 5) 安全性检查
    vector<int> safeSeq;
    bool safe = safetyCheck(available, alloc, need, safeSeq);

    if (safe) {
        // 安全，正式分配已生效（因为我们在原地试分配了）
        printLine('-');
        cout << "试分配后系统状态安全，分配成功。" << endl;
        printState(available, maxNeeds, alloc, need, rname);
        cout << "安全序列：";
        for (size_t i = 0; i < safeSeq.size(); ++i) {
            cout << "P" << safeSeq[i] << (i + 1 == safeSeq.size() ? "" : " -> ");
        }
        cout << "\n系统安全！上述为其中一个安全序列。" << endl;
        outSafeSeq = safeSeq;
        printLine('=');
        return true;
    } else {
        // 不安全，回滚至原状态
        for (int j = 0; j < m; ++j) {
            available[j] += request[j];
            alloc[pid][j] -= request[j];
            need[pid][j] += request[j];
        }
        printLine('-');
        cout << "试分配后系统不安全，分配失败，回滚到请求前状态。" << endl;
        printState(available, maxNeeds, alloc, need, rname);
        cout << "提示：可以稍后在资源充足时重试，或调整请求。" << endl;
        printLine('=');
        return false;
    }
}

// 初始化示例数据（与实验文档中的经典例子一致）：
// n=5, m=3
// Max = {{7,5,3},{3,2,2},{9,0,2},{2,2,2},{4,3,3}}
// Allocation = {{0,1,0},{2,0,0},{3,0,2},{2,1,1},{0,0,2}}
// Available = {3,3,2}
void initSample(vector<vector<int>>& maxNeeds,
                vector<vector<int>>& alloc,
                vector<vector<int>>& need,
                vector<int>& available) {
    maxNeeds = {
        {7,5,3},
        {3,2,2},
        {9,0,2},
        {2,2,2},
        {4,3,3}
    };
    alloc = {
        {0,1,0},
        {2,0,0},
        {3,0,2},
        {2,1,1},
        {0,0,2}
    };
    available = {3,3,2};
    int n = (int)maxNeeds.size();
    int m = (int)available.size();
    need.assign(n, vector<int>(m, 0));
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            need[i][j] = maxNeeds[i][j] - alloc[i][j];
        }
    }
}

// 交互式初始化：用户自定义 n、m、Available、Max、Allocation
void initInteractive(vector<vector<int>>& maxNeeds,
                     vector<vector<int>>& alloc,
                     vector<vector<int>>& need,
                     vector<int>& available,
                     vector<char>& rname) {
    cout << "请输入进程数 n：";
    int n = readInt();
    cout << "请输入资源种类数 m：";
    int m = readInt();

    // 给资源命名，默认 A,B,C,...
    rname.clear();
    for (int j = 0; j < m; ++j) {
        rname.push_back((char)('A' + j));
    }

    // 为避免某些编译器在 assign 上的过度告警，这里使用 resize 进行初始化
    available.clear();
    available.resize(m, 0);
    maxNeeds.clear();
    maxNeeds.resize(n, vector<int>(m, 0));
    alloc.clear();
    alloc.resize(n, vector<int>(m, 0));
    need.clear();
    need.resize(n, vector<int>(m, 0));

    cout << "请依次输入各类资源当前可用数量 Available(";
    for (int j = 0; j < m; ++j) cout << rname[j] << (j + 1 == m ? "" : ", ");
    cout << ")：\n";
    for (int j = 0; j < m; ++j) {
        cout << rname[j] << " = ";
        available[j] = readInt();
        if (available[j] < 0) { available[j] = 0; }
    }

    cout << "请依次输入各进程的最大需求矩阵 Max（按进程逐行输入）\n";
    for (int i = 0; i < n; ++i) {
        cout << "进程 P" << i << " 的 Max(";
        for (int j = 0; j < m; ++j) cout << rname[j] << (j + 1 == m ? "" : ", ");
        cout << ")：\n";
        for (int j = 0; j < m; ++j) {
            maxNeeds[i][j] = readInt();
            if (maxNeeds[i][j] < 0) maxNeeds[i][j] = 0;
        }
    }

    cout << "请依次输入各进程的已分配矩阵 Allocation（按进程逐行输入）\n";
    for (int i = 0; i < n; ++i) {
        cout << "进程 P" << i << " 的 Allocation(";
        for (int j = 0; j < m; ++j) cout << rname[j] << (j + 1 == m ? "" : ", ");
        cout << ")：\n";
        for (int j = 0; j < m; ++j) {
            alloc[i][j] = readInt();
            if (alloc[i][j] < 0) alloc[i][j] = 0;
            if (alloc[i][j] > maxNeeds[i][j]) {
                cout << "警告：P" << i << " 在资源 " << rname[j]
                     << " 上的 Allocation(" << alloc[i][j]
                     << ") 超过 Max(" << maxNeeds[i][j]
                     << ")，已将其截断为 Max。\n";
                alloc[i][j] = maxNeeds[i][j];
            }
        }
    }

    // 计算 Need = Max - Allocation
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            need[i][j] = maxNeeds[i][j] - alloc[i][j];
        }
    }
}

int main() {
    // 资源名称（A、B、C...），仅用于输出
    vector<char> rname;

    // 系统状态四大数据结构
    vector<int> available;              // 可用资源 Available[m]
    vector<vector<int>> maxNeeds;       // 最大需求 Max[n][m]
    vector<vector<int>> allocation;     // 已分配 Allocation[n][m]
    vector<vector<int>> need;           // 仍需 Need[n][m] = Max - Allocation

    cout << "实验二：银行家算法模拟\n";
    printLine();
    cout << "选择初始化方式：\n";
    cout << "1) 使用示例数据（n=5, m=3）\n";
    cout << "2) 自定义输入\n";
    cout << "请输入选项(1/2)：";
    int mode = readInt();

    if (mode == 1) {
        // 准备资源名 A,B,C
        rname = {'A','B','C'};
        initSample(maxNeeds, allocation, need, available);
    } else {
        initInteractive(maxNeeds, allocation, need, available, rname);
    }

    // 主菜单循环
    while (true) {
        printLine();
        cout << "功能菜单：\n";
        cout << "1) 显示当前系统状态并检测安全性\n";
        cout << "2) 提交资源请求（银行家算法）\n";
        cout << "0) 退出\n";
        cout << "请选择：";
        int op = readInt();

        if (op == 0) {
            cout << "已退出程序。" << endl;
            break;
        } else if (op == 1) {
            // 显示状态并做一次安全性检查
            printLine('=');
            cout << "当前系统状态如下：" << endl;
            printState(available, maxNeeds, allocation, need, rname);
            vector<int> safeSeq;
            bool safe = safetyCheck(available, allocation, need, safeSeq);
            if (safe) {
                cout << "系统安全。安全序列：";
                for (size_t i = 0; i < safeSeq.size(); ++i) {
                    cout << "P" << safeSeq[i] << (i + 1 == safeSeq.size() ? "" : " -> ");
                }
                cout << "\n";
            } else {
                cout << "系统不安全（不存在使所有进程顺利完成的序列）。\n";
            }
            printLine('=');
        } else if (op == 2) {
            // 读取一个请求并执行银行家算法
            int n = (int)allocation.size();
            int m = (int)available.size();
            cout << "请输入请求的进程号 pid（0 ~ " << (n - 1) << ")：";
            int pid = readInt();
            vector<int> request(m, 0);
            cout << "请输入请求向量 Request(";
            for (int j = 0; j < m; ++j) cout << rname[j] << (j + 1 == m ? "" : ", ");
            cout << ")：\n";
            for (int j = 0; j < m; ++j) {
                cout << rname[j] << " = ";
                request[j] = readInt();
            }

            vector<int> safeSeq;
            bankerRequest(pid, request, available, allocation, need, maxNeeds, safeSeq, rname);
        } else {
            cout << "无效选项，请重新选择。\n";
        }
    }

    return 0;
}
