PAT甲级 1094 The Largest Generation (25 分)

\quad 树的BFS,注意记录每一层的终止位置(我用-1标识),统计每一层的数量即可。程序如下:

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

const int maxn = 100;
vector<int> v[maxn];

int main(int argc, char const *argv[])
{
	int N, M;
	cin >> N >> M;
	for (int i = 0; i < M; ++i)
	{
		int parent, num;
		cin >> parent >> num;
		for (int j = 0; j < num; ++j)
		{
			int temp;
			cin >> temp;
			v[parent].push_back(temp);
		}
	}
    
    int resNum = 0, resLevel;
    queue<int> q;
    q.push(1);
    int level = 0;
    int count = 0;
    q.push(-1);
    while(!q.empty())
    {
    	int t = q.front();
    	if(t==-1) break;
    	q.pop();
    	count++;
    	for (int i = 0; i < v[t].size(); ++i)
    	{
    		q.push(v[t][i]);
    	}
    	if(q.front()==-1)
    	{
    		level++;
    		if(resNum<count)
    		{
    			resNum = count;
    			resLevel = level;
    		}
    		count = 0;
    		q.pop();
    		q.push(-1);
    	}
    }
    cout << resNum << " " << resLevel << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40438165/article/details/89853852