PAT 1053.Path of Equal Weight

本文介绍了一个使用递归深度优先搜索解决背包问题的C++实现方案。通过定义节点结构体存储物品重量并使用向量记录子节点,实现了对所有可能组合的遍历。采用自定义比较函数对子节点进行排序以优化搜索过程。

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

你怎么那么熟练啊?

#include <cstdio>
#include <queue>
#include <algorithm>
#include <iostream>
#include <time.h>
#include <vector>
using namespace std;

const int maxn = 111;

struct Node{
    int weight;
    vector<int> child;
}node[maxn];
int N,M,S;
vector<int> path;

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

void dfs(int root, int ww)
{
    if(ww>S)
        return;

    if(node[root].child.size()==0)
    {
        if(ww == S)
        {
            for(int i=0;i<path.size();i++)
            {
                if(i==0)
                    printf("%d",path[i]);
                else
                    printf(" %d",path[i]);
            }
            printf("\n");
        }
    }

    sort(node[root].child.begin(), node[root].child.end(), cmp);

    for(int i=0;i<node[root].child.size();i++)
    {
        int tmp = node[root].child[i];
        path.push_back(node[tmp].weight);
        dfs(tmp, ww + node[tmp].weight);
        path.pop_back();
    }

}

int main()
{
    int i,j,k,ch,tmp;
    scanf("%d %d %d",&N,&M,&S);
    for(i=0;i<N;i++)
        scanf("%d",&node[i].weight);

    for(i=0;i<M;i++)
    {
        scanf("%d %d",&j,&k);
        for(ch=0;ch<k;ch++)
        {
            scanf("%d",&tmp);
            node[j].child.push_back(tmp);
        }
    }
    path.clear();
    path.push_back(node[0].weight);
    dfs(0,node[0].weight);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值