ZOJ_3949 Edge to the Root

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;
}
/*
2
6
1 2
2 3
3 4
3 5
3 6
3
1 2
2 3
*/


王的女人

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值