PTA [A1004] Counting Leaves

比较菜的DFS解法。

基本思路就是dfs搜索的时候每进入到子结点时,使深度+1,如果比记录的最大深度大,那么更新一下最大深度。如果存在子结点,那么它就不是叶结点(用flag标记)。

直接贴代码:

#include <iostream>
using namespace std;

const int MAX = 100;
int G[MAX][MAX] = {0}; /* 邻接矩阵存图,反正数据规模不大 */
int res[MAX] = {0}; /* 最后结果 */
int n, m;
int max_depth = 0; /* 记录最大深度,最后输出需要 */

void dfs(int start, int depth){
  int flag = 1; /* 标记是否是叶结点 */
  if(depth > max_depth) max_depth = depth; /* 更新最大深度 */
  for(int i = 1; i < n+1; ++i){
    if(G[start][i] == 1){ 
      flag = 0; /* 存在子节点 */
      dfs(i, depth+1); /* 接着搜索子节点 */
    }
  }
  res[depth] += flag; /* 是叶结点就在本层加一 */
}

int main(){
  cin >> n >> m;
  /* 存图 */
  for(int i = 0 ; i < m; ++i){
    int num, father;
    cin >> father >> num;
    for(int j = 0; j < num; ++j){
      int son;
      cin >> son;
      G[father][son] = 1;
    }
  }
  /* 搜索 */
  dfs(1, 1);
  /* 输出 */
  for(int i = 1; i <= max_depth; ++i){
    cout << res[i];
    if(i != max_depth) cout << ' ';
  }
  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以这样解析出 map 中的 fullDocument 中的 OwnerID、name、QuotaSize: ``` package main import ( "fmt" "reflect" ) func main() { m := map[string]interface{}{ "_id": map[string]interface{}{ "_data": "8263B4EB63000000062B022C0100296E5A1004C3E4524B77B64630AC204C7469FAED7F46645F6964006463B4EB636EBBDB249F2ED2770004", }, "clusterTime": map[string]interface{}{ "1672801123": 6, }, "documentKey": map[string]interface{}{ "_id": "ObjectID(\"63b4eb636ebbdb249f2ed277\")", }, "fullDocument": map[string]interface{}{ "OwnerID": 123, "QuotaSize": 104857600, "_id": "ObjectID(\"63b4eb636ebbdb249f2ed277\")", "directory": "/buckets", "name": "123_test1", }, "ns": map[string]interface{}{ "coll": "UserQuotaConfig", "db": "filer3", }, "operationType": "insert", "wallTime": 1672801123879, } // 取出 fullDocument fullDocument, ok := m["fullDocument"].(map[string]interface{}) if !ok { fmt.Println("fullDocument not found") return } // 取出 OwnerID OwnerID, ok := fullDocument["OwnerID"].(int) if !ok { fmt.Println("OwnerID not found") return } fmt.Println("OwnerID:", OwnerID) // 取出 name name, ok := fullDocument["name"].(string) if !ok { fmt.Println("name not found") return } fmt.Println("name:", name) // 取出 QuotaSize QuotaSize, ok := fullDocument["QuotaSize"].(int) if !ok { fmt.Println("QuotaSize not found") return } fmt.Println("QuotaSize:", QuotaSize) } ``` 在这个例子中,我们首先将 map 赋值给了变量 m。然后使用类型断言取出了 fullDocument 并将其赋
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值