30分压轴题,不算很难,需要对STL有一定的熟练度。
唯一困扰我的是题目要求输出序列要按大小排序,开始想的是用vector的二维数组,但是熟练度不够放弃了,参考了书上的方法在输入子节点的时候就先排序。
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int n, m, s;
struct Node{
int w;
vector<int> child;
}node[101];
vector<int> path;
int sum = 0;
bool cmp(int a, int b){
return node[a].w > node[b].w;
}
void preorder(int index){
path.push_back(node[index].w);
sum += node[index].w;
if(node[index].child.size() == 0){
if(sum == s){
for(vector<int>::iterator it=path.begin(); it!=path.end(); it++){
printf("%d", *it);
if(it != path.end()-1){
printf(" ");
}
}
printf("\n");
}
return;
}
for(int i=0; i<node[index].child.size(); i++){
preorder(node[index].child[i]);
sum -= *(path.end()-1);
path.pop_back();
}
}
int main(){
scanf("%d %d %d", &n, &m, &s);
for(int i=0; i<n; i++){
scanf("%d", &node[i].w);
}
for(int i=0; i<m; i++){
int index, num;
scanf("%d %d", &index, &num);
for(int j=0; j<num; j++){
int c;
scanf("%d", &c);
node[index].child.push_back(c);
}
sort(node[index].child.begin(), node[index].child.end(), cmp);
}
preorder(0);
return 0;
}