hdu 5379 Mahjong tree 树形DP入门
Posted ZhangMengzhi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu 5379 Mahjong tree 树形DP入门相关的知识,希望对你有一定的参考价值。
Description Little sun is an artist. Today he is playing mahjong alone. He suddenly feels that the tree in the yard doesn‘t look good. So he wants to decorate the tree.(The tree has n vertexs, indexed from 1 to n.) Input The first line of the input is a single integer T, indicates the number of test cases. Output For each test case, output one line. The output format is "Case #x: ans"(without quotes), x is the case number, starting from 1. Sample Input
Sample Output
|
题目大意:有一颗n个点的树,在这n个点中填上1~n的数,求满足下列条件的最多填法数量
1、任意节点的所有儿子节点都应填上连续的数。
2、任意子树里面的所有结点都应填上连续的数。
思路:定义dp[u]表示以u为根的子树填上连续的数的填法数量。
对于当前节点u,对于它的儿子节点进行分类讨论:
1、u的儿子节点中如果有超过两个节点不是叶子节点,那么dp[u]=0
2、u只有一个儿子节点v,dp[u] = dp[v]*2;
3、u有两个儿子节点v1,v2,且这两个儿子节点都不是叶子节点,dp[u] = dp[v1]*dp[v2]
……大致思路就是这样,剩下的分类情况略去。
#include <vector> #include<cstdio> #include<cstring> using namespace std; const int maxn = 100005; const int mod = 1e9 + 7; int n; long long dp[maxn]; bool vis[maxn]; vector<int> adj[maxn]; long long solve(int u) { if(dp[u]!=-1) return dp[u]; vis[u] = true; int x=0,v1=-1,v2=-1; dp[u] = 1; int len=adj[u].size(); int son=0; for(int i=0; i<len; i++) { int v = adj[u][i]; if(vis[v]) continue; solve(v); dp[u]*=dp[v]; dp[u]%=mod; if(dp[v]==1) x++; son++; } if(son-x>2||dp[u]==0) return dp[u]=0; else if(son==1) { dp[u]*=2; return dp[u]%=mod; } if(x) { if(son==x||son-x==1) dp[u]*=2; dp[u]%=mod; while(x) { dp[u]*=x; dp[u]%=mod; x--; } } return dp[u]%=mod; } int main() { int T; scanf("%d",&T); int kase=1; while(T--) { scanf("%d",&n); for (int i=1; i<n; i++) { int x,y; scanf("%d%d",&x,&y); adj[x].push_back(y); adj[y].push_back(x); } int root = 1; memset(dp,-1,sizeof(dp)); memset(vis,0,sizeof(vis)); printf("Case #%d: %I64d\n",kase++,solve(root)); for(int i=1; i<=n; i++) adj[i].clear(); //for(int i=1;i<=n;i++) printf("%d %d\n",i,dp[i]); } return 0; }
以上是关于hdu 5379 Mahjong tree 树形DP入门的主要内容,如果未能解决你的问题,请参考以下文章
HDU 5379 Mahjong tree(树的遍历&组合数学)
2015多校第7场 HDU 5379 Mahjong tree 构造,DFS