ZOJ_3949 Edge to the Root
来源:互联网 发布:网络eve什么意思 编辑:程序博客网 时间:2024/06/02 01:41
Edge to the Root
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3949
题意:
给出一棵根为1的树,每条边边长为1。 从根连一条边到某个点,使得各点到根距离的总和最小,求这个最小距离和。
数据:
n (1 ≤ n ≤ 2 × 1e5)树高不超过 3 × 1e4
思路:
1. 树形DP。 2. 考虑到在 X 处加边,受到影响的为 1-X 这条链的中点以下的子树。以X为界把贡献分成两部分。 3. 每次向下移动,对答案的改变为: ( size[mid] - size[y] ) - size[y] (假设从x节点移动到子节点y,y的中点为mid,size[i]为i的子树节点个数) 4. 即 从 mid 到 y 的所有子树节点(不含y的子树)的距离增加1,y 以下的节点的距离全部减1。
代码:
#include <cstdio>#include <math.h>#include <iostream>#include <algorithm>#include <string.h>#include <queue>#include <set>#include <map>using namespace std;typedef long long LL;const int N = 410000;const int M = 100005;const LL INF = 0x3f3f3f3f3f;const int MOD = 1000000007;int n,m;int a,b;int pos;int st[N],cnt;int so[N];LL ans[N];LL dis[N];vector <LL> G[N];void add(int a,int b) {G[a].push_back(b); }void ini(){ memset(ans,0,sizeof ans); memset(so,0,sizeof so); memset(dis,0,sizeof dis); for (int i=0;i<=n;i++) G[i].clear(); pos=1; dis[0]=-1;}void dfs(int x,int pre){ dis[x]=dis[pre]+1; ans[1]+=dis[x]; so[x]=1; for (int i=0;i<G[x].size();i++) { int y=G[x][i]; if (y==pre) continue; dfs(y,x); so[x]+=so[y]; }}void dfs2(int x,int pre){ for (int i=0;i<G[x].size();i++) { int y=G[x][i]; if (y==pre) continue; st[pos++]=y; int mid=pos/2; if (x==1) ans[y]=ans[1]; else ans[y]=ans[x]+so[st[mid+1]]-2*so[y]; dfs2(y,x); pos--; }}int main(){ int cc; scanf("%d",&cc); while (cc--) { scanf("%d",&n); ini(); for (LL i=0;i<n-1;i++) { scanf("%d%d",&a,&b); add(a,b); add(b,a); } dfs(1,0); st[pos++]=1; dfs2(1,0); LL res=INF; for (int i=1;i<=n;i++) res=min(res,ans[i]); printf("%lld\n", res); } return 0;}/*261 22 33 43 53 631 22 3*/
0 0
- ZOJ_3949 Edge to the Root
- zoj3949 Edge to the Root树形dp
- ZOJ 3949 Edge to the Root(树形DP)
- zoj 3949 Edge to the Root 2017浙大校赛B
- how to recover root password in Collabnet SVN Edge?
- 【ZOJ3949 The 17th Zhejiang University Programming Contest B】【树形DP】Edge to the Root 树上加一边 根距离之和尽可能小
- have the edge on
- How to Reset the Root Password
- How to Reset the Root Password 5.5
- The Coming of Edge Computing
- How to reset the root passwd if we forget the root password in red hat
- How to change the root password in Ubuntu
- How to Root the Samsung Galaxy Note 2 (GT-N7100)
- How to compute the square root of an integer?
- How to get the root permission of android
- How to extend the root partition in LVM
- mpg123 /root/We\ belong\ to\ the\ sea.mp3
- How to execute the command with root jurisdiction in pyCharm
- 串口中怎样接收一个完整数据包的解析
- java学生成绩管理系统
- 能不做自己写个类,也叫java.lang.String?
- VS2013+CUDA+TBB
- ViewPager+Fragment动态增加页面,删除页面
- ZOJ_3949 Edge to the Root
- 一种常见的网页防篡改方案
- java中在创建对象时候的初始化顺序
- C# http 性能优化500毫秒到 60 毫秒
- 女生赛hdu6027
- app:transformClasses_enhancedWithInstantReloadDexForDebug
- matlab常用命令汇总
- Fiddler 模拟浏览器提交数据
- 省赛总结