PAT甲1053 Path of Equal Weight (30)(30 分)

本文介绍了一个使用C++实现的深度优先搜索(DFS)算法,该算法用于寻找权重总和等于特定值K的所有可能路径,并将这些路径存储在数组中。文章探讨了在尝试对这些路径进行排序时遇到的段错误问题。

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

对最终整个path数组排序,产生了段错误,不明白为啥……

#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;

struct node
{
    int weight;
    vector<int> child;
    bool leaf;
}A[110];
int N,M,K;

vector<vector<int> >path;
vector<int> temppath;

void DFS(int now,int sum)
{
    if(A[now].leaf==true)
    {
        temppath.push_back(A[now].weight);
        sum+=A[now].weight;
        if(sum==K)
        {
            path.push_back(temppath);
        }
        sum-=A[now].weight;
        temppath.pop_back();
        return;
    }
    temppath.push_back(A[now].weight);
    sum+=A[now].weight;
    for(int i=0;i<A[now].child.size();i++)
    {
        DFS(A[now].child[i],sum);
    }
    temppath.pop_back();
    sum-=A[now].weight;
}

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

int main()
{
    scanf("%d%d%d",&N,&M,&K);
    for(int i=0;i<N;i++)
    {
        scanf("%d",&A[i].weight);
        A[i].leaf=true;
    }
    for(int i=0;i<M;i++)
    {
        int now,num;
        scanf("%d%d",&now,&num);
        for(int j=0;j<num;j++)
        {
            int c;
            scanf("%d",&c);
            A[now].child.push_back(c);
        }
        A[now].leaf=false;
        sort(A[now].child.begin(),A[now].child.end(),cmp);
    }
    DFS(0,0);
    for(int i=0;i<path.size();i++)
    {
        for(int j=0;j<path[i].size();j++)
        {
            if(j!=0)printf(" ");
            printf("%d",path[i][j]);
        }
        printf("\n");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值