P2014 [CTSC1997]选课
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <set> #include <queue> #include <map> #include <sstream> #include <cstdio> #include <cstring> #include <numeric> #include <cmath> #include <iomanip> #include <deque> #include <bitset> #include <cassert> //#include <unordered_set> //#include <unordered_map> #define ll long long #define pll pair<ll, ll> #define pii pair<int, int> #define rep(i,a,b) for(int i=a;i<=b;i++) #define dec(i,a,b) for(int i=a;i>=b;i--) #define forn(i, n) for(int i = 0; i < int(n); i++) using namespace std; int dir[4][2] = { { 1,0 },{ 0,1 } ,{ 0,-1 },{ -1,0 } }; const long long INF = 0x7f7f7f7f7f7f7f7f; const int inf = 0x3f3f3f3f; const double pi = acos(-1.0); const double eps = 1e-6; const ll mod = 1e9 + 7; template<typename T>void read(T & x) { T f = 1; x = 0; char s = getchar(); while (s < '0' || s > '9') { if (s == '-')f = -1; s = getchar(); } while (s >= '0' && s <= '9') { x = x * 10 + s - '0'; s = getchar(); } x *= f; } template<typename T>void print(T x) { if (x < 0) putchar('-'), x = -x; if (x > 9) print(x / 10); putchar(x % 10 + '0'); } /**********************************************************/ const int N = 300 + 5; int n, m; int dp[N][N]; vector<int> g[N]; int dfs(int x) { int sz = 1; for (auto to : g[x]) { int p = dfs(to); dec(i, min(m + 1, sz), 1) { for (int j = 1; j <= p && j + i <= m + 1; j++) { dp[x][i + j] = max(dp[x][i + j], dp[x][i] + dp[to][j]); } } sz += p; } return sz; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif cin >> n >> m; rep(i, 1, n) { int u; cin >> u >> dp[i][1]; g[u].push_back(i); } dfs(0); cout << dp[0][m + 1] << endl; return 0; }