PAT Grade A 1053 Path of Equal Weight (30 points)|C++ implementation

1. Title description

Original title link
Insert picture description here

Input Specification:

Insert picture description here

​​Output Specification:

Insert picture description here

Sample Input:

20 9 24
10 2 4 3 5 10 2 18 9 7 2 2 1 3 12 1 8 6 2 2
00 4 01 02 03 04
02 1 05
04 2 06 07
03 3 11 12 13
06 1 09
07 2 08 10
16 1 15
13 3 14 16 17
17 2 18 19

Sample Output:

10 5 2 7
10 4 10
10 3 3 6 2
10 3 3 6 2

Two, problem-solving ideas

This question examines the knowledge of DFS and trees. Obviously, the title is a tree with point weights. Let us find the route whose total weight is the value given by the title. We can use an array path to store each node in the path. For DFS, the parameters we need to enter are now The number of the operated node, the number of nodes searched before, and the current total point weight. If the total weight of the current point is greater than the number given by the title, return directly. If it is less, DFS is performed on each child of the current node. Since the title requires output from large to small according to the path, the child nodes should also follow the point The right is sorted from largest to smallest. If it is exactly equal to the number given by the title, first determine whether the current node is a leaf node, if not, then return, if it is, then we can output.

Three, AC code

#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 110;
struct Node
{
    
    
    int weight;
    vector<int> child;
}node[maxn];
bool cmp(int a, int b)
{
    
    return node[a].weight > node[b].weight;}
int n, m, s;
int path[maxn];
void DFS(int idx, int numNode, int sum)
{
    
    
    if(sum > s) return;
    if(sum == s)
    {
    
    
        if(node[idx].child.size() != 0) return;
        for(int i=0; i<numNode; i++)
        {
    
    
            printf("%d", node[path[i]].weight);
            if(i < numNode-1)   printf(" ");
            else    printf("\n");
        }
        return;
    }
    for(int i=0; i<node[idx].child.size(); i++)
    {
    
    
        int child = node[idx].child[i];
        path[numNode] = child;
        DFS(child, numNode+1, sum+node[child].weight);
    }
}
int main()
{
    
    
    scanf("%d%d%d", &n, &m, &s);
    for(int i=0; i<n; i++)
        scanf("%d", &node[i].weight);
    int id, k, child;
    for(int i=0; i<m; i++)
    {
    
    
        scanf("%d%d", &id, &k);
        for(int j=0; j<k; j++)
        {
    
    
            scanf("%d", &child);
            node[id].child.push_back(child);
        }
        sort(node[id].child.begin(), node[id].child.end(), cmp);
    }
    path[0] = 0;
    DFS(0, 1, node[0].weight);
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_42393947/article/details/108613915