先任选一个节点作为根,将无根树转换成有根树,代码实现是DFS。
以图9-13的节点i为例,因为是任意选择一个节点做DFS,有以下几种可能:
1.以节点i为根节点,有三个子树
2.以左下方节点为父节点,访问节点i,有两个子树
3.以右下方节点为父节点,访问节点i,有两个子树
4.以右上方节点为父节点,访问节点i,有两个子树
图9-13是按第4中方式DFS,删除节点i之后的连通块有三个,两个子树,以及“上方子树”,从这三个连通块中选一个节点数最大的。
下面是poj 1655 的代码
#define _CRT_SECURE_NO_WARNINGS#include#include #include #include #include #include using namespace std;int N; // 1<= N <= 20000const int maxn = 20000;vector tree[maxn + 5]; // tree[i]表示节点i的相邻节点int d[maxn + 5]; // d[i]表示以i为根的子树的节点个数#define INF 10000000int minNode;int minBalance;void dfs(int node, int parent) // node and its parent{ d[node] = 1; // the node itself int maxSubTree = 0; // subtree that has the most number of nodes for (int i = 0; i < tree[node].size(); i++) { int son = tree[node][i]; if (son != parent) { dfs(son, node); d[node] += d[son]; maxSubTree = max(maxSubTree, d[son]); } } maxSubTree = max(maxSubTree, N - d[node]); // "upside substree with (N - d[node]) nodes" if (maxSubTree < minBalance){ minBalance = maxSubTree; minNode = node; }}int main(){ int t; scanf("%d", &t); while (t--){ scanf("%d", &N); for (int i = 1; i <= N - 1; i++){ tree[i].clear(); } for (int i = 1; i <= N-1; i++){ int u, v; scanf("%d%d", &u, &v); tree[u].push_back(v); tree[v].push_back(u); } minNode = 0; minBalance = INF; dfs(1, 0); // fist node as root printf("%d %d\n", minNode, minBalance); } return 0;}