1 条题解

  • 0
    @ 2025-7-16 9:31:11

    朴素做法

    #include <bits/stdc++.h>
    using namespace std;
    int n, m;
    int u[105], v[105];
    int fa[105];  // 标记每个节点的父节点
    int siz[105]; // 标记每个节点有几个子节点
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(0);
        cin >> n >> m;
        for (int i = 1; i <= m; i++)
        {
            cin >> u[i] >> v[i];
            fa[v[i]] = u[i];
            siz[u[i]]++;
        }
        // 输出根节点
        for (int i = 1; i <= n; i++)
            if (fa[i] == 0)
                cout << i << "\n";
        // 子节点最多的节点
        int ans = 1;
        for (int i = 1; i <= n; i++)
            if (siz[i] > siz[ans])
                ans = i;
        cout << ans << "\n";
        // 遍历所有边,找到 ans 的子节点
        vector<int> now; // 存 ans 的所有子节点
        for (int i = 1; i <= m; i++)
            if (u[i] == ans)
                now.push_back(v[i]);
        sort(now.begin(), now.end());
        // for (int i = 0; i < now.size(); i++)
        //     int x = now[i];
        for (int x : now)
            cout << x << " ";
        return 0;
    }
    

    另一个做法

    #include <bits/stdc++.h>
    using namespace std;
    int n, m;
    int u[105], v[105];
    vector<int> e[105]; // e[u] 存所有 u 的子节点
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(0);
        cin >> n >> m;
        int root = (1 + n) * n / 2; // 初始化为 1~n 之和
        for (int i = 1; i <= m; i++)
        {
            cin >> u[i] >> v[i];
            // 除了根节点之外,其他节点都在子节点位置出现了一次
            root -= v[i];
            // u[i]->v[i],u[i] 多了一个子节点 v[i]
            e[u[i]].push_back(v[i]);
        }
        // 输出根节点
        cout << root << "\n";
        // 子节点最多的节点
        int ans = 1;
        for (int i = 1; i <= n; i++)
            if (e[i].size() > e[ans].size())
                ans = i;
        cout << ans << "\n";
        sort(e[ans].begin(), e[ans].end());
        for (int x : e[ans])
            cout << x << " ";
        return 0;
    }
    
    • 1

    信息

    ID
    555
    时间
    1000ms
    内存
    128MiB
    难度
    3
    标签
    (无)
    递交数
    95
    已通过
    48
    上传者