Last mile of the way(NOIP2017模拟题)
来源:互联网 发布:java飞机大战源代码 编辑:程序博客网 时间:2024/06/09 20:29
小A从仓库里找出了一棵n个点的有根树,1号节点为这棵树的根,树上每个节点的权值为wi,大小为ai。
现在他心中产生了Q个疑问,每个疑问形如在x的子树里,选出一些大小和不超过s的节点(不可以重复选一个节点),最大权值和可以为多少。
输入格式
一行一个整数n。
n−1行两个整数ui, vi表示一条边。
N每行两个整数wi, ai表示这个点的权值和大小。
一行一个整数Q。
每行两个整数x, s,表示一个询问。
输出格式
Q行每行一个整数表示答案
样例输入
样例一
input
5
1 3
2 4
5 3
4 3
2 3
3 2
1 4
5 4
3 1
7
1 5
2 1
2 2
2 3
4 4
3 3
3 5
output
8
0
3
3
5
6
8
限制与约定
10%的数据满足n≤10,s,ai≤10,wi≤10
100%的数据满足n,s,ai≤5000,wi≤10^6,q<=10^5
1s, 512MB
分析:
10分----对每个询问暴力背包DP即可
30分----设f[x][s]表示以x为根节点的子树中取大小和不超过x的节点,最大权值和是多少
F[x][s]=f[c][s’]+f[x][s-s’] (c为子树的节点,合并时的状态转移方程)
时间复杂度为O(ns^2)
100分----之前算法的瓶颈在于合并时的复杂度较高,可以使用启发式合并,每次合并的时候暴力DFS物品较少的子树,直接把一个物品最多的孩子DP数组拷贝到父亲节点的DP 数组上,对于其他孩子暴力DFS,一个一个加进来,复杂度为O(n s log n)
Code
#include<bits/stdc++.h>#define rep(i,a,b) for(int i=a;i<=b;i++)#define dep(i,a,b) for(int i=a;i>=b;i--)#define reg(i,a) for(int i=u[a];i;i=e[i].pre)#define v e[i].to#define LL long long using namespace std;const int maxn=5010;struct edge{int to,pre;}e[maxn<<1];int u[maxn],cnt=0;int n,son[maxn],sz[maxn],w[maxn],l[maxn];LL f[maxn][maxn];inline void ins(int a,int b){ e[++cnt]=(edge){b,u[a]}; u[a]=cnt;}inline int read(){int f=1,x=0;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f;}inline LL maxLL(LL a,LL b){return a>b?a:b;} void dfs(int x,int f){sz[x]=1,son[x]=0;reg(i,x) if(v!=f)dfs(v,x),sz[x]+=sz[v],son[x]=(sz[v]>sz[son[x]]?v:son[x]);//son[x]表示物品最多的子节点编号}void add(int x,int fa,LL f[]){dep(i,maxn-10,l[x]) f[i]=maxLL(f[i],f[i-l[x]]+w[x]);reg(i,x) if(v!=fa) add(v,x,f);}void dp(int x,int fa){reg(i,x) if(v!=fa)dp(v,x);memcpy(f[x],f[son[x]],sizeof(f[x]));//直接拷贝最大的儿子DP数组给父亲节点reg(i,x) if(v!=fa&&v!=son[x]) add(v,x,f[x]);//dfs加上其他子节点的物品dep(j,maxn-10,l[x]) f[x][j]=maxLL(f[x][j],f[x][j-l[x]]+w[x]);}int main(){n=read();rep(i,1,n-1){int a=read(),b=read();ins(a,b);ins(b,a);}rep(i,1,n){w[i]=read(),l[i]=read();}dfs(1,0);dp(1,0);//离线做法int q=read();rep(i,1,q){int x=read(),s=read();cout<<f[x][s]<<endl;}return 0;}
阅读全文
0 0
- Last mile of the way(NOIP2017模拟题)
- OI赛第二场t1Last mile of the way
- The Last Ant(模拟)
- World of our own(NOIP2017模拟题)
- The way of Winning.
- The last day of October
- The last day of 5.1
- The last day of 2015
- The Timeless Way of Building
- the way of learning english
- In the way of SSM
- NOIP2017模拟(7.17)
- NOIP2017模拟(7.11)
- LA 6662 —— The Last Ant(模拟)
- UVA 6662 The Last Ant(模拟退火)
- 【NOIP2017提高A组模拟10.8】Star Way To Heaven(欧几里得距离最小生成树Prim做法)
- The last of the human freedoms
- The last of the Year 2009
- 笨方法学python 习题22、23 整理所学内容
- cogs2098. Asm.Def的病毒解题报告
- 【图论】[luoguP3905]道路重建
- 线性滤波与卷积的基本概念
- 中国剩余定理
- Last mile of the way(NOIP2017模拟题)
- Python函数式编程之filter
- .Net下的 ORM框架介紹
- ES6与ECMA2015的关系
- Spring.NET企业架构实践之 NHibernate + Spring.NET + WCF + Windows服务 + Silverlight 中小企业应用架构完整Demo
- 学习笔记GAN004:DCGAN main.py
- 下载 caffe
- 开源框架完美组合之Spring.NET + NHibernate + ASP.NET MVC + jQuery + easyUI 中英文双语言小型企业网站Demo
- 软件工程导论名词概念