PAT A1053 Path of Equal Weight [DFS tree traversal]

Title Description

Link
given weight and structure of the tree, to find the sum of the weights on the path from the root node to the leaf node and the value equal to a predetermined target number of paths, and outputs a descending path

analysis

  • Static arrays achievements
  • dfs traversal: pay attention to where you want to go back state
  • Two-dimensional array is sorted, the basic vector used to achieve the future in mind and end up writing begin! If vector words
bool cmp(vector<int> a, vector<int> b){
    int len = min(a.size(),b.size());
    for(int i=0;i<len;i++){
        if(a[i] == b[i]) continue
    }
}
sort(ans.begin(), ans.end(), cmp);
  • Finally, of course there is still a one-dimensional array sort, because there is a point after a few, very strange
#include<bits/stdc++.h>
using namespace std;

const int maxn = 105;
struct node{
    int w;
    vector<int> child;
}nodes[maxn];

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

int n,m,s,k,id;

int sum;
vector<vector<int> > ans;
vector<int> path;
void dfs(int i){
    path.push_back(nodes[i].w);
    sum += nodes[i].w;
    if(nodes[i].child.size()==0){
        if(sum == s){
            ans.push_back(path);
        }
        path.pop_back();
        sum -= nodes[i].w;
        return;
    }
    for(int j=0;j<nodes[i].child.size();j++){
        dfs(nodes[i].child[j]);
    }
    path.pop_back();
    sum -= nodes[i].w;
}


int main(){
    cin>>n>>m>>s;
    for(int i=0;i<n;i++){
        cin>>nodes[i].w;
    }
    for(int i=0;i<m;i++){
        cin>>id>>k;
        for(int j=0;j<k;j++){
            int tmp;
            cin>>tmp;
            nodes[id].child.push_back(tmp);
        }
        sort(nodes[id].child.begin(), nodes[id].child.end(), cmp);
    }
    dfs(0);
    for(int i=0;i<ans.size();i++){
        for(int j=0;j<ans[i].size();j++){
            if(j==0) cout<<ans[i][j];
            else cout<<" "<<ans[i][j];
        }
        cout<<endl;
    }

}

Guess you like

Origin www.cnblogs.com/doragd/p/11269755.html