问题

http://hihocoder.com/contest/hiho112/problem/1

问题分析

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
enum{maxn= 100006};
vector<int> tree[maxn];
vector<int> treeLen[maxn];
ll total;
int level[maxn];
int nodeNum[maxn];
int path[maxn];
int N, M;
void dfs(int f)
{
nodeNum[f] = 1;
for (int i=0; i<tree[f].size(); ++i)
{
int v = tree[f][i];
if (level[v] == 0)
{
path[v] = treeLen[f][i]; // 边的长度存储在子树的根节点处。
level[v] = level[f]+1;
dfs(v);
nodeNum[f] += nodeNum[v];
total += (ll)(N-nodeNum[v]) * (ll)nodeNum[v] * (ll)path[v];
}
}
}
void edit(int a, int b, int c)
{
if (level[a] < level[b])
swap(a, b);
int delt = c - path[a];
path[a] = c;
total += (ll)delt * (ll)(N-nodeNum[a]) * (ll)nodeNum[a];
}
int main()
{
scanf("%d %d", &N, &M);
for (int i=0; i<N-1; ++i)
{
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
tree[a].push_back(b);
treeLen[a].push_back(c);
tree[b].push_back(a);
treeLen[b].push_back(c);
}
total =0;
memset(level, 0, sizeof(level));
level[1] = 1;
dfs(1);
char q[100];
for (int i=0; i<M; ++i)
{
scanf("%s", q);
if (q[0] == 'Q')
{
printf("%lld\n", total);
}else
{
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
edit(a, b, c);
}
}
return 0;
}

注意问题

• 本文已收录于以下专栏：

举报原因： 您举报文章：HiHo 112 Total Highway Distance 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)