将自己历史的AC共享
zoj3201 DP题 + DFS
树形DP + DFS
//1891260 2009-06-04 22:48:29 Accepted 3201 C++ 0 228 green tea
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <fstream>
#include <numeric>
#include <iomanip>
#include <bitset>
#include <list>
#include <ctime>
#include <utility>
using namespace std;
#define inf (1<<30)
#define PB push_back
#define mset(x,a) memset(x,(a),sizeof(x))
#define SIZE(X) ((int)X.size())
typedef vector<int> VI;
typedef vector<char> VC;
typedef vector<string> VS;
typedef long long LL;
typedef unsigned long long uLL;
#define twoL(X) (((LL)(1))<<(X))
const double PI=acos(-1.0);
const double eps=1e-11;
template <class T> T sqr(T x) {return x*x;}
template <class T> T gcd(T a, T b) {if(a<0) return (gcd(-a,b)); if(b<0) return (gcd(a,-b)); return (b==0)?a:gcd(b,a%b);}
template <class T> T lcm(T a, T b) {return a*b/gcd(a,b);}
LL toLL(string s) { istringstream sin(s); LL t; sin>>t; return t;}
int toInt(string s) {istringstream sin(s); int t; sin>>t; return t;}
string toString(LL v) {ostringstream sout; sout<<v; return sout.str();}
string toString(int v) {ostringstream sout; sout<<v; return sout.str();}
#define FOREACH(it, a) for(typeof((a).begin()) it = (a).begin(); it!=(a).end(); ++it)
#define ALL(x) ((x).begin, (x).end())
#define cross(a, b, c) ((c).x-(a).x)*((b).y-(a).y)-((b).x-(a).x)*((c).y-(a).y)
#define sq_dist(p, q) ((p).x-(q).x)*((p).x-(q).x)+((p).y-(q).y)*((p).y-(q).y)
VI mat[105];
int w[105], dp[105][105], n, k;
void treedp( int u, int v ) {
for ( int i = k; i >= 1; --i )
for ( int j = 1; j <= i; ++j )
dp[u][i] = max(dp[u][i], dp[u][j]+dp[v][i-j]);
}
void dfs( int v, int u ) {
dp[v][1] = w[v];
for ( int i = 0; i < mat[v].size(); ++i ) {
if ( mat[v][i] != u ) {
dfs(mat[v][i], v);
treedp(v, mat[v][i]);
}
}
}
int main()
{
while ( cin >> n >> k ) {
for ( int i = 0; i < n; ++i ) {
cin >> w[i];
mat[i].clear();
}
int u, v;
for ( int i = 1; i < n; ++i ) {
cin >> u >> v;
mat[u].PB(v);
mat[v].PB(u);
}
mset(dp, -1);
dfs(0, -1);
int ans = -1;
for ( int i = 0; i < n; ++i )
if ( dp[i][k] > ans ) ans = dp[i][k];
cout << ans << endl;
}
return 0;
}
如觉得还有问题 可参考其他相关文章
zoj3201 其他1
zoj3201 其他2
zoj3201 其他3