[POI2008]STA-Station
一道树形dp题。
令dp[u]表示以u为根时所有点的深度之和。考虑u到他的一个子节点v时答案的变化,v子树以外的点的深度都加1,v子树以内的点的深度都减1,所以dp[v] = dp[u] + (n - siz[v]) - siz[v]。于是dp式就搞出来了。
所以两边dfs,第一遍求siz和dp[1],第二遍更新答案。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<cstdio> 2 #include<iostream> 3 #include<cmath> 4 #include<algorithm> 5 #include<cstring> 6 #include<cstdlib> 7 #include<cctype> 8 #include<vector> 9 #include<stack> 10 #include<queue> 11 using namespace std; 12 #define enter puts("") 13 #define space putchar(' ') 14 #define Mem(a, x) memset(a, x, sizeof(a)) 15 #define rg register 16 typedef long long ll; 17 typedef double db; 18 const int INF = 0x3f3f3f3f; 19 const db eps = 1e-8; 20 const int maxn = 1e6 + 5; 21 inline ll read() 22 { 23 ll ans = 0; 24 char ch = getchar(), last = ' '; 25 while(!isdigit(ch)) {last = ch; ch = getchar();} 26 while(isdigit(ch)) {ans = ans * 10 + ch - '0'; ch = getchar();} 27 if(last == '-') ans = -ans; 28 return ans; 29 } 30 inline void write(ll x) 31 { 32 if(x < 0) x = -x, putchar('-'); 33 if(x >= 10) write(x / 10); 34 putchar(x % 10 + '0'); 35 } 36 37 int n, ans = 1; 38 struct Edge 39 { 40 int nxt, to; 41 }e[maxn << 1]; 42 int head[maxn], ecnt = 0; 43 void addEdge(int x, int y) 44 { 45 e[++ecnt] = (Edge){head[x], y}; 46 head[x] = ecnt; 47 } 48 49 int siz[maxn], dep[maxn]; 50 ll dp[maxn]; 51 void dfs1(int now, int f) 52 { 53 siz[now] = 1; 54 for(int i = head[now]; i; i = e[i].nxt) 55 { 56 if(e[i].to == f) continue; 57 dep[e[i].to] = dep[now] + 1; 58 dp[1] += dep[e[i].to]; 59 dfs1(e[i].to, now); 60 siz[now] += siz[e[i].to]; 61 } 62 63 } 64 void dfs2(int now, int f) 65 { 66 for(int i = head[now]; i; i = e[i].nxt) 67 { 68 if(e[i].to == f) continue; 69 dp[e[i].to] = dp[now] + n - (siz[e[i].to] << 1); 70 if(dp[e[i].to] > dp[ans]) ans = e[i].to; 71 dfs2(e[i].to, now); 72 } 73 } 74 75 int main() 76 { 77 n = read(); 78 for(int i = 1; i < n; ++i) 79 { 80 int x = read(), y = read(); 81 addEdge(x, y); addEdge(y, x); 82 } 83 dfs1(1, 0); dfs2(1, 0); 84 write(ans); enter; 85 return 0; 86 }