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

对最终整个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;
}

猜你喜欢

转载自blog.csdn.net/yhy489275918/article/details/81842839