PAT(Advanced Level)A1053. Path of Equal Weight

题意

找树中符合要求路径和的所有路径(终点得是叶子结点),路径要求按照从大到小输出

思路

  • 用DFS做,到根结点统计路径和看是不是符合要求的值,是的话将路径和加入解
  • 递归函数的参数之一target,表示还剩下多少才能到题目要的和
  • 如何按照从大到小输出?
    • sort()函数即可
    • 当然也可以一开始读入孩子的时候就将其进行排序,那么在DFS遍历的时候按照一定顺序就可以是满足从大到小

代码

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#include <queue>
#include <math.h>
using namespace std;
vector<int> weight[110];
int nodes, non_leaf, target;
struct node{
    int weight;     //结点的weight
    vector<int> child;      //结点的所有孩子
};
vector<node> tree;      //存储树
vector<int> path;       //存储路径经过的结点的weight
vector<vector<int>> ans;    //存放所有的解
void dfs(int cur, int target)
{
    if(target < 0)  return;     //已经超出了,就没有必要再往下递归了
    if(tree[cur].child.size() == 0)     //首先得是叶子结点
    {
        if(target != 0)     //其次要满足达到目标和这个条件
            return;
        else{
            path.emplace_back(tree[cur].weight);
            ans.emplace_back(path);
            path.pop_back();
            return;
        }
    }
    path.emplace_back(tree[cur].weight);    //选中当前结点
    for(int i=0;i<tree[cur].child.size();i++)       //扩展状态
    {
        int v = tree[cur].child[i];
        dfs(v, target - tree[v].weight);
    }
    path.pop_back();    //撤销选择
    return;
}
int main()
{
    cin >> nodes >> non_leaf >> target;
    tree.resize(nodes +  10);
    for(int i=0;i<nodes;i++)
        cin >> tree[i].weight;
    int id, t, cnt;
    for(int i=0;i<non_leaf;i++)
    {
        cin >> id >> cnt;
        for(int j=0;j<cnt;j++)
        {
            cin >> t;
            tree[id].child.emplace_back(t);
        }
    }
    dfs(0, target - tree[0].weight);
    sort(ans.begin(), ans.end());
    for(int i=ans.size()-1;i>=0;i--)
    {
        int len = ans[i].size();
        for(int j=0;j<len;j++)
            j == len - 1 ? cout << ans[i][j] : cout << ans[i][j] << " ";
        if(i != 0)  cout << endl;
    }
    return 0;
}

原文地址:https://www.cnblogs.com/MartinLwx/p/13778269.html