BZoj--2435(暴力)

2014-09-01 22:31:12

思路:暴力DFS,学了学邻接表的数组实现。

 1 /*************************************************************************
 2     > File Name: bz2435.cpp
 3     > Author: Nature
 4     > Mail: 564374850@qq.com 
 5     > Created Time: Mon 01 Sep 2014 08:44:53 PM CST
 6 ************************************************************************/
 7 
 8 #include <cstdio>
 9 #include <cstring>
10 #include <cstdlib>
11 #include <cmath>
12 #include <vector>
13 #include <iostream>
14 #include <algorithm>
15 using namespace std;
16 typedef long long ll;
17 const int RA = 1e6;
18 
19 int a,b,c,n;
20 ll ans;
21 bool vis[2 * RA + 5];
22 int now = 1;
23 int head[RA + 5],next[2 * RA + 5],point[2 * RA + 5],val[2 * RA + 5];
24 int tv;
25 
26 inline int Read(){
27     int x = 0; char ch = getchar();
28     while(ch < '0' || ch > '9') ch = getchar();
29     while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0'; ch = getchar();}
30     return x;
31 }
32 
33 void Add(ll x,ll y,ll v){
34     next[++now] = head[x];
35     head[x] = now;
36     point[now] = y;
37     val[now] = v;
38 }
39 
40 int Dfs(int u){
41     int tmp = 0,sum = 0;
42     for(int i = head[u]; i != 0; i = next[i]) if(!vis[i]){
43         vis[i] = vis[i^1] = 1;
44         tmp = Dfs(point[i]);
45         sum += tmp;
46         tv = n - tmp - tmp;
47         ans += (ll)val[i] * (tv > 0 ? tv : -tv);
48     }
49     return sum + 1;
50 }
51 
52 int main(){
53     n = Read();
54     for(int i = 1; i < n; ++i){
55         a = Read(),b = Read(),c = Read();
56         Add(a,b,c);
57         Add(b,a,c);
58     }
59     ans = 0;
60     Dfs(1);
61     printf("%lld\n",ans);
62     return 0;
63 }
64     

 

posted @ 2014-09-01 22:32  Naturain  阅读(114)  评论(0编辑  收藏  举报