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
原创粉丝点击