40分TLE?
查看原帖
40分TLE?
1044254
MinecraftLunar楼主2024/12/7 10:37

Code:

#include <bits/stdc++.h>
// #define LOCAL_RUNNING
#ifdef LOCAL_RUNNING
#define MAXN 10
#else
#define MAXN 100010
#endif
using namespace std;
int fathers[MAXN], n, queryN;
vector<int> sons[MAXN];
bool installed[MAXN];
int install(int pkgNum)
{
    int changeNum = !installed[pkgNum];
    int i = pkgNum;
    installed[i] = 1;
    while (i != fathers[i])
    {
        i = fathers[i];
        changeNum += !installed[i];
        installed[i] = 1;
    }
    return changeNum;
}
int uninstall(int pkgNum)
{
    int changeNum = installed[pkgNum];
    if (sons[pkgNum].empty())
    {
        installed[pkgNum] = 0;
        return changeNum;
    }
    for (size_t i = 0; i < sons[pkgNum].size(); i++)
    {
        changeNum += uninstall(sons[pkgNum][i]);
    }
    installed[pkgNum] = 0;
    return changeNum;
}
int main()
{
    cin >> n;
    for (int i = 1; i < n; i++)
    {
        cin >> fathers[i];
        sons[fathers[i]].push_back(i);
    }
    cin >> queryN;
    vector<int> ans;
    for (int i = 0; i < queryN; i++)
    {
        string operation;
        int pkgNum;
        cin >> operation >> pkgNum;
        if (operation == "install")
        {
            ans.push_back(install(pkgNum));
        }
        else if (operation == "uninstall")
        {
            ans.push_back(uninstall(pkgNum));
        }
    }
#ifdef LOCAL_RUNNING
    puts("-----");
#endif
    for (size_t i = 0; i < ans.size(); i++)
    {
        cout << ans[i] << '\n';
    }
    return 0;
}

maybe not in this method.

2024/12/7 10:37
加载中...