BZOJ1369/LG4395 「BOI2003」Gem 树形DP
2024-09-05 03:52:13
问题描述
题解
发现对于结点 \(x\) ,其父亲,自己,和所有的孩子权值不同,共 \(3\) 类,从贪心的角度考虑,肯定是填 \(1,2,3\) 这三种。
于是套路树形DP,设 \(opt[x][1/2/3]\) 代表以 \(x\) 为根的子树中,且 \(x\) 标为 \(0/1/2\) 的最小值。
\(\mathrm{Code}\)
#include<bits/stdc++.h>
using namespace std;
template <typename Tp>
void read(Tp &x){
x=0;char ch=1;int fh;
while(ch!='-'&&(ch>'9'||ch<'0')) ch=getchar();
if(ch=='-') ch=getchar(),fh=-1;
else fh=1;
while(ch>='0'&&ch<='9') x=(x<<1)+(x<<3)+ch-'0',ch=getchar();
x*=fh;
}
const int maxn=10007;
const int maxm=20007;
int n;
int Head[maxn],to[maxm],Next[maxm],tot;
int opt[maxn][4];
void add(int x,int y){
to[++tot]=y,Next[tot]=Head[x],Head[x]=tot;
}
void dp(int x,int f){
for(int i=1;i<=3;i++) opt[x][i]=i;
for(int i=Head[x];i;i=Next[i]){
int y=to[i];
if(y==f) continue;
dp(y,x);
opt[x][1]+=min(opt[y][2],opt[y][3]);
opt[x][2]+=min(opt[y][1],opt[y][3]);
opt[x][3]+=min(opt[y][1],opt[y][2]);
}
}
int main(){
read(n);
for(int i=1,x,y;i<n;i++){
read(x);read(y);
add(x,y);add(y,x);
}
dp(1,0);
printf("%d\n",min(opt[1][1],min(opt[1][2],opt[1][3])));
return 0;
}
最新文章
- Ajax缓存解决办法(转载)
- CSS中的display属性
- CSS中的a标签几个访问状态记录
- js判断浏览器种类以及版本号(从jquery1.8中抠出来的)
- [Node.js] Broswerify -- 1
- LightOj 1282 Leading and Trailing
- [转载](iPhone开发)Bundle Display Name 改为中文。ap
- 原生app,WEBAPP,混合app
- BZOJ 1083: [SCOI2005]繁忙的都市(MST)
- HDU - 1248 寒冰王座 数学or暴力枚举
- 【一天一道LeetCode】#109. Convert Sorted List to Binary Search Tree
- Socket编程实践(10) --select的限制与poll的使用
- STM32的USART应用问题(不定时添加)
- python中文件处理--判断文件读取结束方法
- wx.chooseImage
- bat语法集【转】
- python 多进程的启动和代码执行顺序
- drupal7 STMP邮件模块配置
- Python学习---django惰性机制
- vb编写串口调试程序
热门文章
- go路由httprouter中的压缩字典树算法图解及c++实现
- Java 基础复习 -- Enum 类
- vue中监听路由参数的变化
- iOS中dealloc原理
- AlertDialog创建对话框的测试
- LeetCode刷题191123
- Redis &; memcached PK
- pytest系列(四)- pytest+allure+jenkins - 持续集成平台生成allure报告
- Codeforces Round #590 D. Distinct Characters Queries
- HTML5 3D 在智慧物业/地产管理系统中的应用