本文主要是介绍The more, The Better 树上背包,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
传送门
题目描述
ACboy很喜欢玩一种战略游戏,在一个地图上,有N座城堡,每座城堡都有一定的宝物,在每次游戏中ACboy允许攻克M个城堡并获得里面的宝物。但由于地理位置原因,有些城堡不能直接攻克,要攻克这些城堡必须先攻克其他某一个特定的城堡。你能帮ACboy算出要获得尽量多的宝物应该攻克哪M个城堡吗?
分析
树上背包问题,建立一个虚根即可
代码
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 1e3 + 10;
const ll mod= 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a){char c=getchar();T x=0,f=1;while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
while(isdigit(c)){x=(x<<1)+(x<<3)+c-'0';c=getchar();}a=f*x;}
int gcd(int a,int b){return (b>0)?gcd(b,a%b):a;}
int h[N],ne[N],e[N],idx;
int n,m;
bool st[N];
int f[N][N];void add(int x,int y){ne[idx] = h[x],e[idx] = y,h[x] = idx++;
}void dfs(int u){st[u] = true;for(int i = h[u];~i;i = ne[i]){int v = e[i];if(st[v]) continue;dfs(v);for(int j = m + 1;j >= 2;j--)for(int k = 1;k < j;k++)if(f[u][k] != -1 && f[v][j - k] != -1){f[u][j] = max(f[u][j],f[u][k] + f[v][j - k]);}}
}int main(){while(scanf("%d%d",&n,&m) && (m != 0 && n != 0)){memset(h,-1,sizeof h);memset(st,0,sizeof st);memset(f,-1,sizeof f);idx = 0;for(int i = 0;i <= n;i++) f[i][0] = 0;f[0][1] = 0;for(int i = 1;i <= n;i++){int x,y;read(x),read(y);add(x,i);f[i][1] = y;}dfs(0);di(f[0][m + 1]);}return 0;
}/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ + + + +Code is far away from
* ┃ ┃ + bug with the animal protecting
* ┃ ┗━━━┓ 神兽保佑,代码无bug
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/
这篇关于The more, The Better 树上背包的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!