1. 程式人生 > >1004. Counting Leaves (30)

1004. Counting Leaves (30)

space 若是 數組 vector memset front pos ack emp

思路:

1.

先建樹

比如利用 vector<vector<int>> v;

v[node].size() 即為葉子的判別條件

2.

利用bfs逐層判斷節點是否為葉子節點,若是則level數組對應的位置加一

3.

求出深度並打印

#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;

vector
<vector<int>> v; int n,m; queue<int> q; int level[100]; int mh=0; void bfs(int l) { while(q.empty() != true) { int newnode=q.front(); //pop並不會返回元素 q.pop(); if(v[newnode].size() == 0) { level[l]++; continue; } for(int i =0;i<v[newnode].size();i++) { q.push(v[newnode][i]); bfs(l
+1); } } } int gethigh(int h,int node){ if(v[node].size() == 0) mh=max(h,mh); for(int i =0;i<v[node].size();i++) { gethigh(h+1,v[node][i]); } } int main() { scanf("%d %d",&n,&m); v.resize(n+1); memset(level,0,100); //建樹 for(int i=0;i<m;i++) { int
id,k; scanf("%d %d",&id,&k); for(int j =0;j<k;j++) { int ch; scanf("%d",&ch); v[id].push_back(ch); } } q.push(1); bfs(0); gethigh(0,1); // printf("mh:%d\n",mh); for(int i=0;i<=mh;i++) { i == 0? printf("%d",level[i]):printf(" %d",level[i]); } return 0; }

技術分享圖片

1004. Counting Leaves (30)