1094 The Largest Generation (25)(25 分)

BFS:添加层变量,最后遍历数组找到最大的,注意最大范围要包括n

#include
#include
#include
using namespace std;
const int maxn = 1000;
struct node {
    vectorchild;
    int layer;
}Node[maxn];
int n, m;
int Layer[maxn];
void BFS(int root)
{
    queueq;
    q.push(root);
    while (!q.empty())
    {
        int top = q.front();
        q.pop();
        Layer[Node[top].layer]++;
        for (int i = 0; i < Node[top].child.size(); i++)
        {
            int child = Node[top].child[i];
            Node[child].layer = Node[top].layer + 1;
            q.push(child);
        }
    }
}
int main()
{
    scanf("%d%d", &n, &m);
    for (int i = 0; i < m; i++)
    {
        int id, k;
        scanf("%d%d", &id, &k);
        while (k--)
        {
            int x;
            scanf("%d", &x);
            Node[id].child.push_back(x);
        }
    }
    Node[1].layer = 1;
    BFS(1);
    int maxnum = 0, maxlayer;
    for (int i = 1; i <= n; i++)
    {
        if (Layer[i] > maxnum)maxnum = Layer[i], maxlayer = i;
    }
    printf("%d %d", maxnum, maxlayer);
    return 0;
}

DFS解法:

#include
#include
#include
using namespace std;
const int maxn = 1000;
struct node {
    vectorchild;
}Node[maxn];
int n, m;
int Layer[maxn];
void DFS(int root,int layer)
{
    Layer[layer]++;
    for (int i = 0; i < Node[root].child.size(); i++)
    {
        int child = Node[root].child[i];
        DFS(child, layer + 1);
    }
}
int main()
{
    scanf("%d%d", &n, &m);
    for (int i = 0; i < m; i++)
    {
        int id, k;
        scanf("%d%d", &id, &k);
        while (k--)
        {
            int x;
            scanf("%d", &x);
            Node[id].child.push_back(x);
        }
    }
    DFS(1,1);
    int maxnum = 0, maxlayer;
    for (int i = 1; i <= n; i++)
    {
        if (Layer[i] > maxnum)maxnum = Layer[i], maxlayer = i;
    }
    printf("%d %d", maxnum, maxlayer);
    return 0;
}

你可能感兴趣的:(1094 The Largest Generation (25)(25 分))