树形dp题目汇总

详细算法见:https://user.qzone.qq.com/50222268/blog/1503921896

 

1.题目:https://www.luogu.org/problemnew/show/P2014#sub

如何将普通树变成兄弟二叉树:

无父节点的节点为 n+1

​
for (int i=1; i<=n; ++i) {

        int a, b;

        cin >> a >> b;

        if (a == 0)    a = n + 1;

        score[i] = b;
        brother[i] = child[a];//i节点的兄弟为其父节点a的孩子
        child[a] = i;

}


​

 

 

代码:

#include 
#include 
#include 

using namespace std;

struct node
{
	int wei,l,r;
};

const int maxSize=300;
int n,m;
int vis[maxSize+5][maxSize+5],f[maxSize+5][maxSize+5];
node N[maxSize+5];

void dfs(int x,int y)
{
	int i,j;
	
	if (vis[x][y]==1)//防止重复搜 
		return ;
	vis[x][y]=1;
	
	if (x==0 || y==0)
		return ;
	
	dfs(N[x].r,y);	//不选x节点
	f[x][y]=f[N[x].r][y];
	
	for (i=0;i

 

2.题目:https://www.luogu.org/problemnew/show/P2015#sub

此题要注意把边权化点权

#include 
#include 
#include 
#include 

using namespace std;

struct node
{
	int wei,y;
};
struct node1
{
	int l,r,wei;
};

const int maxSize=100;
int n,q;
int vis[maxSize+5],visit[maxSize+5][maxSize+5],f[maxSize+5][maxSize+5];
node1 a[maxSize+5];
vector  N[maxSize+5];

void read(int x)
{
	int i;
	node n1;
	
	for (i=0;i

 

3.题目:https://www.luogu.org/problemnew/show/P1352#sub

#include 
#include 
#include 
#include 

using namespace std;

struct node
{
	int y,wei;//wei指y的权重 
};

const int maxSize=6000;
vector  N[maxSize+5];
int n;
int a[maxSize+5],ru[maxSize+5],vis[maxSize+5],f[maxSize+5][2];
//f 0去 1不去 
void dfs(int x)
{
	int i,f1=0,f0=0;
	node n1;
	
	for (i=0;i

 

4.完美服务器

gfoj---course---动态规划2

注意状态转移方程可以化简

写程序时方程不能特判!!!

原因:

1,此方程是递推出来的,所以不能特判

2,若不满足则直接上maxValue,此处maxValue不能过大。。。

 

代码:

#include 
#include 
#include 
#include 
using namespace std;

const int maxSize=10000,maxValue=1000000;
vector  N[maxSize+5];
int vis[maxSize+5],f[maxSize+5][3];

void dfs(int x)
{
	int i,y;
	
	for (i=0;i

 

5.寻宝:

https://blog.csdn.net/scutbenson/article/details/81738322

 

6.行动!行动!

https://blog.csdn.net/scutbenson/article/details/81745008

你可能感兴趣的:(练手系列,树形dp)