51nod 1737 配对(树的重心)

求出来树的重心,计算重心到每个点的距离加和。
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值