题目链接:Problem - 1437D - Codeforces
题意:
有一棵由n个顶点组成的树,它的根在顶点1。BFS可以用下面的伪代码来描述。有一个顶点序列,即BFS算法访问的顶点的顺序(伪代码中的数组a)同时每个顶点的所有子节点都被按升序查看。
a = [] // 顶点被处理的顺序
q = Queue()
q.put(1) //把根放在队列的末尾
while not q.empty():
k = q.pop() // 从队列中获取第一个顶点
a.append(k) // 将k添加到顶点访问序列的末尾
for y in g[k]: //g[k]是顶点k的所有子节点的列表,按升序排序
q.put(y)
多组输入
有一棵由n(2≤n≤2e5) 个顶点组成的树,它的根在顶点1,有一个顶点序列,即BFS算法访问的顶点的顺序(伪代码中的数组a)(且1≤ai≤n; ai≠aj; a1=1)同时每个顶点的所有子节点都被按升序查看。求出这个按BFS顺序排序的树的最小高度。
题解:
因为它给的BFS是按照升序访问子节点的,那么对于每个点后面出现的节点,如果它后面的点比他的编号还小,说明要新开一层,否则就一直堆在一层。所以按照题意,把每一个高度的字节点全部遍历完,只要发现当前序列大于前一个,就说明要一个新的上层根节点cnt,没有大于就记录这层的节点数目now,如果上层根节点用完了cnt == sum,那么ans++,根节点就变成了我们记录的节点数目sum = now,cnt重新变成0,继续循环下去,直到遍历完成。便可以得到该树的最小高度。
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string.h>
#include<map>
#include<queue>
#include<vector>
#include<set>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
const ll mm = 2e5 + 60;
ll a[mm];
int n;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--)
{
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
int ans = 1, cnt = 0, sum = 1, now = 0;
for (int i = 2; i <= n; i++) {
if (a[i] > a[i - 1]) now++;
else {
cnt++;
if (cnt == sum)
{
ans++;
sum = now;
cnt = 0;
}
}
}
cout << ans << endl;
}
return 0;
}