一刷
# include <iostream>
# include <queue>
# include <vector>
# include <algorithm>
using namespace std;
typedef int INDEX;
struct node{
int weight;
vector< INDEX> child;
} Node[ 105 ] ;
int N, M, S;
vector< INDEX> path;
void DFS ( INDEX idx, int weightSum) {
if ( Node[ idx] . child. size ( ) == 0 ) {
if ( weightSum == S) {
for ( size_t i = 0 ; i< path. size ( ) ; ++ i) {
cout << Node[ path[ i] ] . weight;
if ( i != path. size ( ) - 1 )
cout << " " ;
else
cout << endl;
}
}
return ;
}
for ( size_t i = 0 ; i< Node[ idx] . child. size ( ) ; ++ i) {
INDEX cld = Node[ idx] . child[ i] ;
if ( weightSum + Node[ cld] . weight <= S) {
path. push_back ( cld) ;
DFS ( cld, weightSum + Node[ cld] . weight) ;
path. pop_back ( ) ;
}
}
}
int main ( void ) {
cin >> N >> M >> S;
for ( int i = 0 ; i< N; ++ i) {
scanf ( "%d" , & Node[ i] . weight) ;
}
INDEX id, cid;
int K;
for ( int i = 0 ; i< M; ++ i) {
scanf ( "%d" , & id) ;
scanf ( "%d" , & K) ;
for ( int j = 0 ; j< K; ++ j) {
scanf ( "%d" , & cid) ;
Node[ id] . child. push_back ( cid) ;
}
sort ( Node[ id] . child. begin ( ) , Node[ id] . child. end ( ) , [ ] ( INDEX a, INDEX b) { return Node[ a] . weight > Node[ b] . weight; } ) ;
}
path. push_back ( 0 ) ;
DFS ( 0 , Node[ 0 ] . weight) ;
return 0 ;
}
二刷:精炼了很多
# include <bits/stdc++.h>
using namespace std;
int N, M, S;
vector< int > G[ 101 ] ;
int weight[ 101 ] ;
vector< int > rst;
void DFS ( int u, int sumW) {
if ( sumW > S) return ;
if ( G[ u] . size ( ) == 0 && sumW == S) {
rst. push_back ( u) ;
for ( int i = 0 ; i < rst. size ( ) ; ++ i)
cout << weight[ rst[ i] ] << ( i == rst. size ( ) - 1 ? "\n" : " " ) ;
rst. pop_back ( ) ;
return ;
}
rst. push_back ( u) ;
for ( int v: G[ u] )
DFS ( v, sumW + weight[ v] ) ;
rst. pop_back ( ) ;
}
int main ( ) {
cin >> N >> M >> S;
for ( int i = 0 ; i < N; ++ i)
scanf ( "%d" , & weight[ i] ) ;
for ( int i = 0 ; i < M; ++ i) {
int u, K, v;
scanf ( "%d %d" , & u, & K) ;
for ( int j = 0 ; j < K; ++ j) {
scanf ( "%d" , & v) ;
G[ u] . push_back ( v) ;
}
sort ( G[ u] . begin ( ) , G[ u] . end ( ) , [ ] ( int a, int b) { return weight[ a] > weight[ b] ; } ) ;
}
DFS ( 0 , weight[ 0 ] ) ;
return 0 ;
}