【POJ 1655】 Balancing Act
【题目链接】
【算法】
树形DP求树的重心
【代码】
#include <algorithm> #include <bitset> #include <cctype> #include <cerrno> #include <clocale> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <exception> #include <fstream> #include <functional> #include <limits> #include <list> #include <map> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stdexcept> #include <streambuf> #include <string> #include <utility> #include <vector> #include <cwchar> #include <cwctype> #include <stack> #include <limits.h> using namespace std; #define MAXN 20010 int i,T,n,u,v,ans,pos; vector<int> E[MAXN]; int size[MAXN]; template <typename T> inline void read(T &x) { int f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; } for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x*= f; } template <typename T> inline void write(T x) { if (x < 0) { putchar('-'); x = -x; } if (x > 9) write(x/10); putchar(x%10+'0'); } template <typename T> inline void writeln(T x) { write(x); puts(""); } inline void dfs(int x,int fa) { int i,son,m=0; size[x] = 1; for (i = 0; i < E[x].size(); i++) { son = E[x][i]; if (son != fa) { dfs(E[x][i],x); size[x] += size[son]; if (size[son] > m) m = size[son]; } } if (n - size[x] > m) m = n - size[x]; if (m < ans) { ans = m; pos = x; } } int main() { read(T); while (T--) { read(n); for (i = 1; i <= n; i++) E[i].clear(); for (i = 1; i < n; i++) { read(u); read(v); E[u].push_back(v); E[v].push_back(u); } ans = 2e9; dfs(1,0); printf("%d %d\n",pos,ans); } return 0; }