51nod 1737 配对(树的重心)

来源:互联网 发布:mg汽车 知乎 编辑:程序博客网 时间:2024/06/05 06:31

求出来树的重心,计算重心到每个点的距离加和。
tle了老长时间,把数组开大两倍后,就过了。
一直以为是代码矬,结果是内存开小了。调试期间还搜了别人题解,发现还有更好的做法。
我的:

#include <bits/stdc++.h>using namespace std;template <class T>inline bool scan_d(T &ret){    char c;    int sgn;    if(c=getchar(),c==EOF) return 0; //EOF    while(c!='-'&&(c<'0'||c>'9')) c=getchar();    sgn=(c=='-')?-1:1;    ret=(c=='-')?0:(c-'0');    while(c=getchar(),c>='0'&&c<='9') ret=ret*10+(c-'0');    ret*=sgn;    return 1;}inline void out(long long x){    if(x>9) out(x/10);    putchar(x%10+'0');}const int MAXN = 200100;struct Edge{    int to,next,w;} edge[MAXN];int head[MAXN],tot;int son[MAXN],n,root=1,temp;long long res = 0;void addedge(int u, int v, int w){    edge[tot].to = v;    edge[tot].w = w;    edge[tot].next = head[u];    head[u] = tot++;}void init(){    memset(head, -1, sizeof(head));    tot = 0;}void dfs(int u, int fa){    int v,tmp = 0;    son[u] = 1;    for(int i = head[u]; i != -1; i = edge[i].next)    {        int v = edge[i].to;        if(v == fa) continue;        dfs(v,u);        son[u] += son[v];        tmp = max(tmp,son[v]);    }    tmp = max(tmp,n-son[u]);    if(tmp < temp)    {        temp = tmp;        root = u;    }}void solve(int u, int fa, long long len){    int v;    res += len;    for(int i = head[u]; i != -1; i = edge[i].next)    {        v = edge[i].to;        if(v == fa) continue;        solve(v,u,len+edge[i].w);    }}int main(){    scan_d(n);    init();    temp = n;    int u,v,w;    for(int i = 0; i < n-1; ++i)    {        scan_d(u);        scan_d(v);        scan_d(w);        addedge(u,v,w);        addedge(v,u,w);    }    dfs(1,-1);    solve(root,-1,0);    out(res);    return 0;}

模仿的别人的:
http://www.cnblogs.com/enigma-aw/p/6275197.html

#include <bits/stdc++.h>using namespace std;const int MAXN = 200100;struct Edge{    int to,next,w;};Edge edge[MAXN];int head[MAXN],tot;int son[MAXN];int n;void addedge(int u, int v, int w){    edge[tot].to = v;    edge[tot].next = head[u];    edge[tot].w = w;    head[u] = tot++;}long long res = 0;void dfs(int u, int fa){    son[u] = 1;    int v;    for(int i = head[u]; i != -1; i = edge[i].next)    {        v = edge[i].to;        if(v == fa) continue;        dfs(v,u);        son[u] += son[v];        res += edge[i].w*(long long)min(son[v],n-son[v]);    }}int main(){    ios::sync_with_stdio(false);    cin >> n;    memset(head,-1,sizeof(head));    tot = 0;    int u,v,w;    for(int i = 0; i < n-1; ++i)    {        cin >> u >> v >> w;        addedge(u,v,w);        addedge(v,u,w);    }    dfs(1,-1);    cout << res << endl;    return 0;}