bzoj2435: [Noi2011]道路修建 树上dp
RE了一辈子...
思路:树上dp,直接dfs找到每个点v的子节点有多少, 那么对答案的贡献是 w*abs((n-size[v])-size[v]);
RE代码:
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const int maxn = 1100000; 5 6 vector<pair<ll,ll> > E[maxn<<1]; 7 ll size[maxn]; 8 ll n,ans; 9 bool vis[maxn]; 10 11 inline ll read() 12 { 13 ll x=0,f=1;char ch=getchar(); 14 while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} 15 while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} 16 return x*f; 17 } 18 19 void dfs(ll u){ 20 size[u] = 1; 21 for(int i=0; i<E[u].size(); i++){ 22 int v = E[u][i].first, w = E[u][i].second; 23 if(!vis[v]){ 24 vis[v] = 1; 25 dfs(v); 26 size[u] += size[v]; 27 ans+=(ll)(w*(ll)abs((ll)(size[v]-(n-size[v])))); 28 } 29 } 30 } 31 32 int main(){ 33 n = read(); 34 for(int i=1; i<n; i++){ 35 ll u,v,w; u=read(),v=read(),w=read(); 36 E[u].push_back(make_pair(v,w)); 37 E[v].push_back(make_pair(u,w)); 38 } 39 vis[n] = 1; 40 dfs(n); 41 cout << ans << endl; 42 }