題目背景
SOURCE:NOIP2015-HN-CJZX
題目描述
樹(tree)是指由 n 個點,n-1 條邊構成的連通無向圖。如果有一棵樹,它的每一條邊 (u,v) 都有一個權值 lu,v ,我們把這樣的樹稱作帶權樹(weighted tree)。
我們知道對於樹上的任意兩個點,他們之間的路徑是唯一的。對於兩個點 u,v 來說,我們可以算出 u 與 v 之間的路徑上所有邊權之和,將其稱作 u 與 v 之間路徑的長度,記作 d(u,v)。
你的任務是計算:
輸入格式:
輸入第一行爲一個正整數 n 。
接下來 n-1 行,每行三個非負整數 x,y,w,表示點 x 與點 y 之間有一條權值爲 w 的一條邊。
保證輸入的圖是一棵樹。
輸出格式:
輸出僅包含一行一個數,即答案。因爲結果可能很大,請將答案模 100 000 007 輸出。
EG 1
in:
4
1 2 4
1 3 4
1 4 4
out:
72
EG 2
in:
10
1 2 1320321
2 3 4687651
3 4 1321357
4 5 6651332
5 6 5746513
6 7 5674687
7 8 7451216
8 9 7789965
9 10 8765134
out:
28244404
備註
【樣例1說明】
d(1,2)+d(1,3)+d(1,4)=4+4+4=12
d(2,1)+d(2,3)+d(2,4)=4+8+8=20
d(3,1)+d(3,2)+d(3,4)=4+8+8=20
d(4,1)+d(4,2)+d(4,3)=4+8+8=20
所以答案爲:12+20+20+20=72。
【數據範圍】
共 20 個測試點,其數據特徵如下表所示。
對所有數據,有 1≤n≤3×105,0≤w<100 000 007。數據有一定梯度。
題解:
代碼:
#include<bits/stdc++.h>
using namespace std;
const long long mod=100000007;
struct node
{
int u,to,next;
long long w;
}a[600005];
long long l,n;
long long first[300005],son[300005],fa[300005];
long long ans;
inline void add(long long x,long long y,long long z)
{
a[++l].to=y;
a[l].u=x;
a[l].next=first[x];
a[l].w=z;
first[x]=l;
}
inline void dfs(int root)
{
for(int i=first[root];i;i=a[i].next)
if(a[i].to!=fa[root])
{
fa[a[i].to]=root;
dfs(a[i].to);
son[root]+=son[a[i].to];
}
}
int main()
{
cin>>n;
for(int i=2;i<=n;++i)
{
long long x,y,z;
cin>>x>>y>>z;
add(x,y,z);
add(y,x,z);
son[i]=1;
}
son[1]=1;
dfs(1);
for(int i=1;i<=l;++i)
{
int o=min(son[a[i].to],son[a[i].u]);
long long j=(long long)o*(long long)(n-o);
j*=a[i].w%mod;
ans+=j%mod;
}
cout<<ans%mod<<endl;
return 0;
}