PAT甲级-树的遍历-1053 Path of Equal Weight解题思路

1053 Path of Equal Weight (30 分)

在这里插入图片描述
在这里插入图片描述

思路

PAT还是很严谨的,有个sort的id写成了i,PAT一直有个测试点没过,但牛客网可以过,太坑了。。

这里有个sort,对结构体的vector进行排序,非常妙,用到了node里面的权重值对vector排序

代码

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

const int maxn = 110;
struct node{
    int weight;
    vector<int>child;
}Node[maxn];

int N,M,K;
int path[maxn]={0};

int num;
void DFS(int index,int weight_sum,int depth)
{
    weight_sum = weight_sum+Node[index].weight;
    path[depth] = Node[index].weight;
    
    if(Node[index].child.size()==0)
    {
        if(weight_sum == K)
        {
            for(int i=0;i<depth;i++)
            {
                cout<<path[i]<<" ";
            }
            cout<<path[depth]<<endl;
        }
    }
    else 
    {
        for(int j=0;j<Node[index].child.size();j++)
        {
            DFS(Node[index].child[j],weight_sum,depth+1);
        }
    }
    
}


bool cmp(int a,int b)
{
    return Node[a].weight>Node[b].weight;
}

int main()
{
    int id,number,ch;
    cin>>N>>M>>K;
    for(int i =0;i<N;i++)
    {
        cin>>number;
        Node[i].weight = number;
    }
    for(int i =0;i<M;i++)
    {
        cin>>id>>number;
        for(int j=0;j<number;j++)
        {
            cin>>ch;
            Node[id].child.push_back(ch);
        }
        sort(Node[id].child.begin(),Node[id].child.end(),cmp);
    }
    DFS(0,0,0);
   
}




  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wujiekd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值