pat甲级1053,路径问题,背包问题,深度优先搜索

博客探讨了PAT甲级1053题目的解决方案,涉及树的数据结构设计,包括节点的权值和vector型孩子表示。通过深度优先搜索(DFS)算法遍历树,当路径总和等于目标权重且当前节点无孩子时输出路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据结构

  • 静态树。树中有权值以及vector型的孩子。
  • vector来放孩子。
  • hashpath数组。用来放置路径

算法

  • 使用DFS(),来遍历这棵树。如果参数中的sum,等于题目要求的weight值,同时该节点没有孩子了,就一次输出。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <stdio.h>
#include <math.h>
#include <queue>
#include <stack>
#include <cstring>
#include <cmath>
using namespace std;

int hashset[100];//结果集
int w;
struct node
{
    int weight;
    vector<int> child;
} Node[100];
void DFS(int root,int numofNode,int sum)
{
    if(sum==w)
    {
        if(Node[root].child.size()>0)
        {
            return;
        }
        else
        {

            for(int i=0; i<numofNode; i++)
            {
                printf("%d",Node[hashset[i]].weight);
                if (i<numofNode-1)
                {
                    printf(" ");
                }
                else
                {
                    printf("\n");
                }


            }

            return;
        }
    }
    if(sum>w)
        return;
    for(int i=0; i<Node[root].child.size(); i++)
    {
        int child;
        child=Node[root].child[i];
        hashset[numofNode]=child;
        DFS(child,numofNode+1,sum+Node[child].weight);
    }
}
bool cmp(int a,int b)
{
    return Node[a].weight>Node[b].weight;
}
int main()
{
    int num;
    int n;

    scanf("%d%d%d",&num,&n,&w);

    for(int i=0; i<num; i++)
    {
        scanf("%d",&Node[i].weight);
    }
    for(int i=0; i<n; i++)
    {
        int id,k;
        scanf("%d %d",&id,&k);
        for(int j=0; j<k; j++)
        {
            int x;
            scanf("%d",&x);
            Node[id].child.push_back(x);
        }
        sort(Node[id].child.begin(),Node[id].child.end(),cmp);
    }
    //hashset[0]=0;
    DFS(0,1,Node[0].weight);//结点,个数,该点的值;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值