PAT 1042 Path of Equal Weight (30)

题目

题目描述

解题思路

  • 1.dfs遍历就行了,重点是要设置出一种结构,方便你进行遍历。
    例如我这里结构如下:
    struct node
    {
    int value, father, sum;
    bool visited,isLeaf;
    vector<int> children;
    node() :value(-1),father(-1),sum(0),visited(false),isLeaf(true){}
    };

    其中father是为了方便输出用的,sum和visited也让程序变得更方便。
  • 2.输入要求值从大到小输出,所以我这里遍历的时候就从大到小遍历,详细请看代码。

代码

#include<iostream>
#include<vector>
#include<deque>
#include<algorithm>
using namespace std;
int n, m, s;

struct node
{
    int value, father, sum;
    bool visited,isLeaf;
    vector<int> children;
    node() :value(-1),father(-1),sum(0),visited(false),isLeaf(true){}
};
vector<node> a;
//这个感觉很神奇,居然真的可以实现,children里面保存的是孩子的id,然后我这里借助a,按照孩子中的value值,从大到小进行排序
bool cmp(int k1, int k2)
{
    return a[k1].value > a[k2].value;
}
void prin(int k)
{
    vector<int> b;
    b.push_back(k);
    int father = a[k].father;
    while (father!=-1)
    {
        b.push_back(father);
        father = a[father].father;
    }
    int k1 = (int)(b.size()-1);
    bool flag = false;
    for (; k1>=0; k1--)
    {
        if (!flag)
        {
            cout << a[b[k1]].value;
            flag = true;
        }
        else
            cout << " " << a[b[k1]].value;
    }

}
void dfs(int k)
{
    a[k].visited = true;
    if (k == 0) a[k].sum = a[k].value;
    else
        a[k].sum = a[a[k].father].sum + a[k].value;
    if (a[k].isLeaf)
    {
        if (a[k].sum == s)
        {
            //cout << "find:" <<k << endl;
            prin(k);
            cout << endl;
        }
        return;
    }
    else
    {
        //依照孩子中value的值从大到小进行遍历,解决了输出的要求问题
        for (int i = 0; i < (int)a[k].children.size(); i++)
        {
            int children_id = a[k].children[i];
            if (!a[children_id].visited)
                dfs(children_id);
        }
    }
}
int main()
{
    //输入
    cin >> n >> m >> s;
    a.resize(n);
    for (int i = 0; i < n; i++)
        cin >> a[i].value;
    int tem_id, tem_numOfChild;
    for (int i = 0; i < m; i++)
    {
        cin >> tem_id >> tem_numOfChild;
        a[tem_id].children = vector<int>(tem_numOfChild);
        a[tem_id].isLeaf = false;
        for (int i = 0; i < tem_numOfChild; i++)
        {
            cin >> a[tem_id].children[i];
            a[a[tem_id].children[i]].father = tem_id;
        }
        //根据value,对children进行排序。
        sort(a[tem_id].children.begin(), a[tem_id].children.end(), cmp);
    }
    //遍历并输出
    dfs(0);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值